#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>
#include <pthread.h>
#include <semaphore.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <stdarg.h>
#include <errno.h>
#include <stdbool.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <net/if.h>
#include <sys/ioctl.h>
#include <ctype.h>
#include "type.h"
#include "apis.h"
#include "cli_main.h"
#include "zhongdunData.h"
#include "xml_conf.h"
#include "buf_misc.h"
#include "device.h"
#include "cmd.h"
#include "cli.h"
#include "listHandle.h"
#include "dataHandle.h"
#include "uploadListHandle.h"
#include "auth.h"
#include "ftpUpload.h"
#include "importantLog.h"
#include "./../flexapi/zhongdun_xa/zhongdun_xa_msgHandler.h"
extern I8 *up_cache;
extern I8 *up_back;
extern I8 *upCurrentData;
extern I8 *log_file;
char authIdentifier[1024] = {0};
size_t authIdentifierLength = 0;
static I32 log_level = CLI_LOG_DEFAULT;
static CMD_QUEUE *cmd_queue_free = NULL;
static CMD_QUEUE *cmd_queue = NULL;
static I8 *cmd_queue_tmp = NULL;
static I32 disable_auth = 0;//if disable_auth == 0 means have to auth 
static EVENT_QUEUE event_queue[EVENT_QUEUE_SIZE];
static I32 event_queue_s = 0;
static I32 event_queue_e = 0;
static int restart_time = 10; //wait 10s to restart device
static sem_t sem_eventq;
static sem_t sem_main;
static pthread_t cli_app_thread;
static I32 devStatus = HT_CL_STATUS_OK;
//up_time[0] is last up time, 
//up_time[1] is current time.
//up_time[2] is last data time.
static time_t up_time[3];
static I32 max_time_missed;
//historical_time[0] is begin time
//historical_time[1] is end time
static time_t historical_time[2];
pthread_mutex_t mutex;
static time_t idle_time[2];
I8 dev_mac[32] = {0};
I32 fd_times = 0;
I32 countSendImsi = 0;
//static I32 upload_num[CELL_NUM];
bool readyCleanDb = false;
static I32 up_back_time = 0;
//auth

static I32 update_ip = 0;
int MAX_DATA_PER_FRAME = 50;
const char *loglevel[8] = 
{
    "EMERGENCY",
    "ALERT",
    "CRITICAL",
    "ERROR",
    "WARNING",
    "NOTICE",
    "INFO",
    "DEBUG"
} ;
static U16 reconnectCode = SYSTEM_POWER_ON;
static RECORDINFO recordInfo;
static MACRECORDINFO macRecordInfo;
 I32 cmdClearFlag = 0; //this is a flag to make sure clear all cmd
 I8 *srvcmd;
 static I32 powerSlot = 0;
static bool upload_data = true;
static FILE *log = NULL;
static bool BlackListEnable = false;
static bool powerEnable[7] = {false, false, false, false, false, false,false};
static I32 upgradeFailTm = 0;
DEV_STATUS dev_status;
COMMANDLIST cmdList;
I32 slotNum[9];
ZHONGDUNLIST mobileList;
ZHONGDUNLIST unicomList;
GPSBOARDINFO gpsboardinfo;

const char *restartCauseFile = "/mnt/usr/restartCause.tmp";
bool createRestartCauseFileByCode(U16 code)
{
    if (access(restartCauseFile, F_OK) == 0)
    {
        unlink(restartCauseFile);
    }
    FILE *fd = NULL;
    fd = fopen(restartCauseFile, "a");
    if (fd == NULL)
    {
        return false;
    }
    fprintf(fd, "%d", code);
    fclose(fd);
    return true;
}

void getRestartCauseFileCode()
{
    if (access(restartCauseFile, F_OK) == 0)
    {
        FILE *fd = NULL;
        fd = fopen(restartCauseFile, "r");
        if (fd == NULL)
            return;
        I8 buf[DEV_INFO_NUM_LEN] = {0};
        if (fread(buf, 1, 1, fd) != 0)
        {
            return;
        }
        buf[1]='\0';
        fclose(fd);
        reconnectCode = atoi(buf);
        cli_app_log(CLI_LOG_CRITICAL, "last reboot casue code is %d \n", reconnectCode);
        unlink(restartCauseFile);
    }    

}

static void cleanCmdList()
{
    memset(&cmdList, 0, sizeof(COMMANDLIST));
    cmdList.commandNum = 0;
    cmdList.cmdIndex = 0;
}
static I32 cmd_queue_init(void)
{
	I32 i;
	
    cmd_queue_tmp = malloc(CMD_QUEUE_SIZE * sizeof(CMD_QUEUE));
    if (cmd_queue_tmp == NULL) 
	{
       	cli_app_log(CLI_LOG_CRITICAL, "ERROR allocate command queue\n");
        return -1;
    }	
	cmd_queue_free = (CMD_QUEUE *) cmd_queue_tmp;
    for (i = 0; i < (CMD_QUEUE_SIZE - 1); i++) 
	{
        cmd_queue_free[i].next = (CMD_QUEUE *) (&cmd_queue_free[i + 1]);
    }	
    cmd_queue_free[i].next = NULL;
    return 0;
}

static I32 cmd_queue_exit(void)
{
    free(cmd_queue_tmp);
    cmd_queue_free = NULL;
    cmd_queue = NULL;
    return 0;
}

static I32 cmd_queue_add(I32 fcode, I32 socket, I32 timeout, I32 dcode, I32 id, I32 type)
{
    CMD_QUEUE *tmp;
    I32 ret = IF_APP_ERROR;
    if (cmd_queue_free != NULL) 
    {
        tmp = cmd_queue_free;
        cmd_queue_free = cmd_queue_free->next;		
        tmp->fcode = fcode;
        tmp->socket = socket;
        tmp->timeout = timeout;
        tmp->dcode = dcode;
        tmp->id = id;
        tmp->state = HT_CL_STATUS_START;
        tmp->type = type;
        tmp->next = cmd_queue;
        cmd_queue = tmp;
        ret = IF_APP_OK;
    }
    cli_app_log(CLI_LOG_INFO, "<<<<<<<<<<<<<<<<<<<<<<cmd_queue_add dcode == %04x, id == %d>>>>>>>>>\n", dcode, id);
    return ret;
}

static I32 cmd_queue_set_status(I32 dcode, I32 id, I32 state, I32 * socket, I32 *type)
{
	CMD_QUEUE *tmp = cmd_queue;
    CMD_QUEUE *tmp1;
    I32 ret = IF_APP_ERROR;
    if (tmp == NULL) 
	{
        return ret;
    }
    if (tmp->id == id && tmp->dcode == dcode) 
	{
        *socket = tmp->socket;
        *type = tmp->type;
        tmp->state = state;		
        ret = IF_APP_OK;
    } 
    else 
	{
        while (tmp->next != NULL) 
		{
            tmp1 = tmp->next;
            if (tmp1->id == id && tmp1->dcode == dcode) 
			{
                *socket = tmp1->socket;
                *type = tmp1->type;
                tmp1->state = state;
				ret = IF_APP_OK;
                break;
            } 
            else 
			{
                tmp = tmp->next;
            }
        }
    }
    return ret;
}

void getmac(char *eth1Mac, char *mac12)
{
    int sockfd;
    struct ifreq tmp;   
    char devMac[20] = {0};
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if( sockfd < 0)
    {
        cli_app_log(CLI_LOG_WARNING, "create socket fail\n");
        return ;
    }

    memset(&tmp,0,sizeof(struct ifreq));
    strncpy(tmp.ifr_name, "eth1",sizeof(tmp.ifr_name)-1);
    if( (ioctl(sockfd,SIOCGIFHWADDR,&tmp)) < 0 )
    {
        cli_app_log(CLI_LOG_WARNING, "mac ioctl for %s error\n","eth1");
        close(sockfd);
        return ;
    }
    close(sockfd);

    sprintf(devMac, "%02x%02x%02x%02x%02x%02x",
            (unsigned char)tmp.ifr_hwaddr.sa_data[0],
            (unsigned char)tmp.ifr_hwaddr.sa_data[1],
            (unsigned char)tmp.ifr_hwaddr.sa_data[2],
            (unsigned char)tmp.ifr_hwaddr.sa_data[3],
            (unsigned char)tmp.ifr_hwaddr.sa_data[4],
            (unsigned char)tmp.ifr_hwaddr.sa_data[5]
            );
    int i = 0, j = 0;
    for (; i < 12; i++)
    {
        eth1Mac[j++] =  toupper(devMac[i]);
        mac12[i] = toupper(devMac[i]);
        if ( i%2 != 0 && i != 0 && i != 11)
        {
             eth1Mac[j++] = '-';
        }
    }
    
    cli_app_log(CLI_LOG_WARNING, "mac is %s \n", eth1Mac);
    

}

static I32 cmd_queue_find_status(I32 state)
{
	CMD_QUEUE *tmp = cmd_queue;
    CMD_QUEUE *tmp1;
    I32 ret = IF_APP_ERROR;
	
    if (tmp == NULL) 
	{
        return ret;
    }
	
    if (tmp->state == state) 
	{		
        ret = IF_APP_OK;
    } 
    else 
	{
        while (tmp->next != NULL) 
	    {
            tmp1 = tmp->next;
            if (tmp1->state == state) 
			{				
                ret = IF_APP_OK;
                break;
            } 
            else 
			{
                tmp = tmp->next;
            }
        }
    }
	return ret;
}

static I32 cmd_queue_del(I32 dcode, I32 id, I32 * socket, I32 *type)
{
    CMD_QUEUE *tmp = cmd_queue;
    CMD_QUEUE *tmp1;
    I32 ret = IF_APP_ERROR;	
    if (tmp == NULL) 
	{
        return ret;
    }	
    if (tmp->id == id && tmp->dcode == dcode) 
	{
        *socket = tmp->socket;
        *type = tmp->type;
        ret = tmp->fcode;		
        cmd_queue = tmp->next;
        tmp->next = cmd_queue_free;
        cmd_queue_free = tmp;

    } 
    else 
	{
        while (tmp->next != NULL) 
		{
            tmp1 = tmp->next;
           	if (tmp1->id == id && tmp1->dcode == dcode) 
			{
                *socket = tmp1->socket;
                *type = tmp1->type;
                ret = tmp->fcode;				
                tmp->next = tmp1->next;
                tmp1->next = cmd_queue_free;
                cmd_queue_free = tmp1;
                break;
            } 
            else 
			{
                tmp = tmp->next;
            }
        }
    }
	cli_app_log(CLI_LOG_INFO, "<<<<<<<<<<<<<<<<<<<<<<cmd_queue_del dcode == %04x, id == %d>>>>>>>>>\n", dcode, id);
	return ret;
}

#if 0
//todo, move cmd timeout to timer, not here, because we have already added this timeout.
static I32 cmd_queue_timeout(I32 tick)
{

    CMD_QUEUE *tmp1, *tmp2;

    tmp1 = cmd_queue;
    if (tmp1 == NULL) {
        return 0;
    }

    tmp2 = tmp1->next;
    while (tmp2 != NULL) {
        tmp2->timeout -= tick;
        if (tmp2->timeout <= 0) {
            tmp1->next = tmp2->next;
            tmp2->next = cmd_queue_free;
            cmd_queue_free = tmp2;
            tmp2 = tmp1->next;
        } else {
            tmp1 = tmp2;
            tmp2 = tmp2->next;
        }
    }

    tmp1 = cmd_queue;
    tmp1->timeout -= tick;
    if (tmp1->timeout <= 0) {
        cmd_queue = tmp1->next;
        tmp1->next = cmd_queue_free;
        cmd_queue_free = tmp1;
    }

    return 0;
}
#endif

static I32 event_queue_init(void)
{
    event_queue_e = 0;
    event_queue_s = 0;
    sem_init(&sem_eventq, 0, 1);
	return 0;
}

static I32 event_queue_exit(void)
{
    sem_wait(&sem_eventq);
    event_queue_e = 0;
    event_queue_s = 0;
    sem_post(&sem_eventq);
    sem_destroy(&sem_eventq);
	return 0;
}

I32 event_queue_add(I32 module, I32 socket, I32 len, I8 * data)
{
    if( (module != IF_APP_EVENT_TIMER) && (module != IF_APP_EVENT_TIMEOUT) )
    {
        cli_app_log(CLI_LOG_INFO, "module=0x%X socket=0x%X len=%d\n", module, socket, len);

        if( len > 0 )
        {
           //	buffer_dump_log(data, len, CLI_LOG_INFO);
        }
    }

    sem_wait(&sem_eventq);
    event_queue[event_queue_s].module = module;
    event_queue[event_queue_s].socket = socket;
    event_queue[event_queue_s].len = len;
    event_queue[event_queue_s].data = data;
	
    if (++event_queue_s >= EVENT_QUEUE_SIZE)
	{
        event_queue_s = 0;
    }

    sem_post(&sem_eventq);
    sem_post(&sem_main);
 
    return 0;
}

static I32  time_substract(struct timeval *result, struct timeval *begin,struct timeval *end)
{

    if(begin->tv_sec > end->tv_sec)    
        return -1;

    if((begin->tv_sec == end->tv_sec) && (begin->tv_usec > end->tv_usec))    
        return -2;

    result->tv_sec    = (end->tv_sec - begin->tv_sec);
    result->tv_usec    = (end->tv_usec - begin->tv_usec);
    if(result->tv_usec < 0)
    {
        result->tv_sec--;
        result->tv_usec += 1000000;
    }
    return 0;
}

static void initRecordList()
{

    recordInfo.maxId = recordInfo.minId = recordInfo.realNum = 0;
    getRecordMaxIdAndMinId(&recordInfo.maxId, &recordInfo.minId, DATA_TYPE_IMSI);
    recordInfo.lastId = recordInfo.maxId ;
    macRecordInfo.maxId = macRecordInfo.minId = macRecordInfo.realNum = 0;
    getRecordMaxIdAndMinId(&macRecordInfo.maxId, &macRecordInfo.minId, DATA_TYPE_MAC);
    macRecordInfo.lastId = macRecordInfo.maxId ;
    cli_app_log(CLI_LOG_INFO, "get record id success imsi  maxId : %d minId : %d  mac maxId : %d mac minId : %d\n", 
                recordInfo.maxId, recordInfo.minId, macRecordInfo.maxId, macRecordInfo.minId);
}


static void handle_recv_data(PHONE_TMP *tmp)
{
    I32 num = 0, i = 0;
    num = tmp->num;
    if ( num == 0)
    {
        return ;
    }
    struct timeval start, stop, diff;
    memset(&start, 0, sizeof(struct timeval));
    memset(&stop, 0, sizeof(struct timeval));
    memset(&diff, 0, sizeof(struct timeval));
    gettimeofday(&start, 0);
    I32 recordNum = recordInfo.maxId;
    sqliteStartTransaction();

    PHONE_DATA *pdata;
    pdata = (PHONE_DATA *)tmp->data;

    for ( i = 0; i < num; i++ )
    {
        if ( !savePhoneInfo( ++recordInfo.maxId, pdata->time_low, (I8 *)pdata->imsi,
                             (I8 *)pdata->imei, pdata->slotId) )
        {
            recordInfo.maxId--;        
        }
        pdata++;
    }
    if ( !sqliteCommitTransaction() )
    {
        recordInfo.maxId = recordNum;
        cli_app_log(CLI_LOG_INFO, "sqlite commit data failed \n");
    }

    gettimeofday(&stop, 0);
    time_substract(&diff, &start, &stop);
    cli_app_log(CLI_LOG_DEFAULT, "Total time is  : %d s , %d us \n", (I32)diff.tv_sec, (I32)diff.tv_usec);
}

static void handle_zhongdun_data(PHONE_TMP *tmp)
{

    mobileList.num = 0;
    unicomList.num = 0;
    zhongdunHandleRecord(tmp, &mobileList, &unicomList);
    if (cli_get_mng_status() == MNG_SERVER_STATUS_CONNECTED)
    {
        if (mobileList.num != 0)
            send_imsi_data(true, (I8 *)&mobileList, upCurrentData);
    }
    if (cli_get_data_status() == DATA_SERVER_STATUS_CONNECTED)
    {
        if (unicomList.num != 0)
            send_imsi_data(false, (I8 *)&unicomList, upCurrentData);        
    }
    
}

static void handle_location_status(I32 conf_req)
{
    switch(conf_req)
    {
        case REQUEST_TDD_LOCATION_ON:
            dev_status.tddLocationEnable = 1;
            break;

        case REQUEST_TDD_LOCATION_OFF:
            dev_status.tddLocationEnable = 0;
            break;

        case REQUEST_FDD_LOCATION_ON:
            dev_status.fddLocationEnable = 1;
            break;

        case REQUEST_FDD_LOCATION_OFF:
            dev_status.fddLocationEnable = 0;
            break;

        default:
            break;

    }


}

static void handle_recv_mac_data(PHONE_TMP *tmp)
{
    I32 num = 0, i = 0;
    num = tmp->num;
    if ( num == 0)
    {
        return ;
    }
    struct timeval start, stop, diff;
    memset(&start, 0, sizeof(struct timeval));
    memset(&stop, 0, sizeof(struct timeval));
    memset(&diff, 0, sizeof(struct timeval));
    gettimeofday(&start, 0);
    I32 recordNum = macRecordInfo.maxId;
    sqliteStartTransaction();

    MAC_DATA *pdata;
    pdata = (MAC_DATA *)tmp->data;

    for ( i = 0; i < num; i++ )
    {
        if ( !saveMacInfo( ++macRecordInfo.maxId, pdata->time_low, (I8 *)pdata->mac) )
        {
            macRecordInfo.maxId--;        
        }
        pdata++;
    }
    if ( !sqliteCommitTransaction() )
    {
        macRecordInfo.maxId = recordNum;
        cli_app_log(CLI_LOG_INFO, "sqlite commit data failed \n");
    }

    gettimeofday(&stop, 0);
    time_substract(&diff, &start, &stop);
    cli_app_log(CLI_LOG_DEFAULT, "Total time is  : %d s , %d us \n", (I32)diff.tv_sec, (I32)diff.tv_usec);
}

void handle_recv_data_from_cli(I32 *rstTime, I32 *funCode, I32 *cmdType)
{
    I8 *buf = NULL;
    I32 buf_len, len = 0;
    I32 auth_rst;
    I32 cli_req;

    I32 *type = cmdType; //is this cmdType
    I32 *cli_rst_times = rstTime;
    I32 *fcode = funCode;

    //here, it just unit test. process is: create rcv thread---> create mng socket--->might data socket. done
    //correct process is: create rcv thread ---> create auth socket and shake hand --->create mng socket -->create data socket.
    if ((buf = event_queue[event_queue_e].data) == NULL || (buf_len = event_queue[event_queue_e].len) == 0) 
    {
        if (event_queue[event_queue_e].socket == CLI_THREAD_CREATING) 
		{
			if (cli_init(&dev_conf, CLI_THREAD_CREATING) != IF_APP_OK) 
			{           
			    //todo: add timer to restart cli init process.
                timer_queue_add(TIMER_OUT_RESTART_CREATE_PTHREAD,TIMER_ID_RESTART_CREATE_PTHREAD, 0, 0, 0, 0); 
                return;
			}
			else
			{
				event_queue_add(IF_APP_EVENT_INIT_CLI, CLI_INIT_AUTH, 0, NULL);
				return;
			}
		}
		
		if (event_queue[event_queue_e].socket == CLI_INIT_AUTH)
		{
			if ((buf = buffer_allocate()) == NULL) 
			{
				cli_app_log(CLI_LOG_CRITICAL, "init_cli: get buffer fail\n");
            	return;
        	}
        	
			//start auth
			if ((disable_auth = atoi(dev_conf.auth.disable_auth)) == 0)
			{
				cli_app_log(CLI_LOG_NOTICE, "start auth\n");
				len = cmd_gen_devinfo_string(&dev_conf.dev, reconnectCode, buf);
                if (get_host_by_server(dev_conf.auth.addr) == NULL)
                {
                    timer_queue_add(TIMER_OUT_RESTART_AUTH, TIMER_ID_RESTART_AUTH, 0, 0, 0, 0);   
					buffer_free(buf);
					return;
    
                }
				auth_rst = auth_init(buf, len, dev_conf.auth.cer_file, get_host_by_server(dev_conf.auth.addr), atoi(dev_conf.auth.port), authIdentifier, &authIdentifierLength);
	
				if (auth_rst != 0)
				{
					cli_app_log(CLI_LOG_ERROR, "auth faild, auth_rst:%d\n", auth_rst);
                    if (update_ip == 1)
                    { 
                        update_ip = 2;
                        xml_config_overwirte(CONFIG_MODE_RESTORE);
                        xml_get_devConf(&dev_conf);
                    }
                    
                    timer_queue_add(TIMER_OUT_RESTART_AUTH, TIMER_ID_RESTART_AUTH, 0, 0, 0, 0);   
					buffer_free(buf);
					return;
				}
			}
			     		
            //start mng server connection
			buffer_free(buf);
            if (strcmp(dev_conf.dev.protocol, NANFEI) != 0)
            {
                cli_set_mng_status(MNG_SERVER_STATUS_CONNECTING);
                if (strcmp(dev_conf.dev.protocol, ZHONGDUN) == 0)
                {
                    cli_set_data_status(DATA_SERVER_STATUS_CONNECTING);
                }
                else
                    timer_queue_add((TIMEOUT_SRV_DEAD(atoi(dev_conf.mng.hb)) + TIMEOUT_SRV_DEAD(atoi(dev_conf.mng.hb))),
                            TIMER_ID_MNG_DEAD, 0, 0, 0, 0);
            }
            else
            {
                cli_set_data_status(DATA_SERVER_STATUS_CONNECTING);
            }
			//because some times, server will not send welcome message, so start server dead timer here.
        }
        if (event_queue[event_queue_e].socket == CLI_INIT_MNG)
            cli_set_mng_status(MNG_SERVER_STATUS_CONNECTING);
        if (event_queue[event_queue_e].socket == CLI_INIT_DATA)
            cli_set_data_status(DATA_SERVER_STATUS_CONNECTING);
	    
        return;
    }
    
	cli_app_log(CLI_LOG_INFO, "received cli init data from socket:%d, data: %s\n", 
	event_queue[event_queue_e].socket,buf);
    
	cli_req = cmd_handle_register_msg(buf, buf_len);
	if(cli_req == IF_APP_WELCOME_MSG) 
	{
        *cli_rst_times = 0;
		if (cli_get_mng_status() == MNG_SERVER_STATUS_WAITING_WELCOME && 
		    cli_sock_is_mng(event_queue[event_queue_e].socket) != IF_APP_ERROR) 
		{	
			if (disable_auth == 0)
			{
                cli_app_log(CLI_LOG_INFO, "identifier is %s \n", authIdentifier);
				cli_send_to_tcp(event_queue[event_queue_e].socket, authIdentifier, authIdentifierLength, 1);
			}
			                            					
			len = cmd_gen_devinfo_string(&dev_conf.dev, reconnectCode, buf);
            cli_send_to_mng(buf, len);
    
			//start data server connection
            if (strcmp(dev_conf.dev.protocol, CAIPIN) == 0 || strcmp(dev_conf.dev.protocol, ZHIHUI) == 0 
                || strcmp(dev_conf.dev.protocol, KUANGUANG) == 0 || strcmp(dev_conf.dev.protocol, CAIPINNEW) == 0 
                || strcmp(dev_conf.dev.protocol, HUANSHUO) == 0 || strcmp(dev_conf.dev.protocol, WANGXUN) == 0
                || strcmp(dev_conf.dev.protocol, FENGHUO) == 0 || strcmp(dev_conf.dev.protocol, RENZIXING) == 0
                || strcmp(dev_conf.dev.protocol, JINFENG) == 0 || strcmp(dev_conf.dev.protocol, GAOKE) == 0
                || strcmp(dev_conf.dev.protocol, BAIZHUO) == 0 || strcmp(dev_conf.dev.protocol, LOCATION) == 0
                || strcmp(dev_conf.dev.protocol, ZISHUO) == 0)

            {
                cli_set_data_status(DATA_SERVER_STATUS_CONNECTING);
                timer_queue_add(TIMEOUT_SRV_DEAD(atoi(dev_conf.mng.hb)), TIMER_ID_DATA_DEAD, 0, 0, 0, 0);
            }
            else if (strcmp(dev_conf.dev.protocol, LEGU) == 0 ||
				     strcmp(dev_conf.dev.protocol, XINAN) == 0 || 
                     strcmp(dev_conf.dev.protocol, ZHONGDUN) == 0)
            {
                 //wait for reigster success

            }
			//because some times, server will not send welcome message, so start server dead timer here.
            
		} 
		else if (cli_get_data_status() == DATA_SERVER_STATUS_WAITING_WELCOME && 
		         cli_sock_is_data(event_queue[event_queue_e].socket) != IF_APP_ERROR) 
		{				
			if(disable_auth == 0)
			{
				cli_send_to_tcp(event_queue[event_queue_e].socket, authIdentifier, authIdentifierLength, 1);		
            }	
            if (strcmp(dev_conf.dev.protocol, NANFEI) != 0)
            {
                len = cmd_gen_devinfo_string(&dev_conf.dev, reconnectCode, buf);
                cli_send_to_data(buf, len);
            }
            else
            {
                cli_set_data_status(DATA_SERVER_STATUS_CONNECTED);
                timer_queue_add(TIMEOUT_DATA_INTVL(atoi(dev_conf.data.itvl)), TIMER_ID_DATA_HEART_BEAT, 0, 0, 0, 0);
                timer_queue_add(TIMEOUT_DATA_INTVL(atoi(dev_conf.data.itvl)) + 300, TIMER_ID_SEND_OLD_DATA, 0, 0, 0, 0);

            }
		} 
		else 
		{
			cli_app_log(CLI_LOG_ERROR, "received duplicate welcome message\n");		
		}
	} 
	else if (cli_req == IF_APP_REG_SUCCESS) 	
	{
		if (cli_sock_is_mng(event_queue[event_queue_e].socket) != IF_APP_ERROR) 
		{
			cli_set_mng_status(MNG_SERVER_STATUS_CONNECTED);
			timer_queue_add(TIMEOUT_MNG_INTVL(atoi(dev_conf.mng.hb)), TIMER_ID_MNG_HEART_BEAT, 0, 0, 0, 0);
            if (strcmp(dev_conf.dev.protocol, LEGU) == 0)
            {
                cli_set_data_status(DATA_SERVER_STATUS_CONNECTED);
			    timer_queue_add(TIMEOUT_DATA_INTVL(atoi(dev_conf.data.itvl)), TIMER_ID_DATA_HEART_BEAT, 0, 0, 0, 0);
                timer_queue_add(TIMEOUT_DATA_INTVL(atoi(dev_conf.data.itvl)) + 300, TIMER_ID_SEND_OLD_DATA, 0, 0, 0, 0);
                if (strcmp(dev_conf.dev.protocol, ZHONGDUN) == 0)
                {
                    //len = cmd_hanldle_device_requestMsg(CMD_OTHERS, DEVICE_REQ_BTS_INFO, buf);
                    //cli_send_to_mng(buf, len);                
                }
            }
            else if (strcmp(dev_conf.dev.protocol, XINAN) == 0)
            {
                //use ftp 
                len = cmd_hanldle_device_requestMsg(CMD_OTHERS, DEVICE_REQ_TIMESYNC, buf);
                cli_send_to_mng(buf, len); 
            }
    
		} 
		else if (cli_sock_is_data(event_queue[event_queue_e].socket) != IF_APP_ERROR) 
        {
			cli_set_data_status(DATA_SERVER_STATUS_CONNECTED);
            if (strcmp(dev_conf.dev.protocol, ZHONGDUN) == 0)
                timer_queue_add(TIMEOUT_MNG_INTVL(atoi(dev_conf.data.hb)), TIMER_ID_DATA_HEART_BEAT, 0, 0, 0, 0);
            if (atoi(dev_conf.dev.uploadMode) != 2 && strcmp(dev_conf.dev.protocol, ZHONGDUN) != 0 &&  strcmp(dev_conf.dev.protocol, BAIZHUO) != 0)
            {
			    timer_queue_add(TIMEOUT_DATA_INTVL(atoi(dev_conf.data.itvl)), TIMER_ID_DATA_HEART_BEAT, 0, 0, 0, 0);
                timer_queue_add(TIMEOUT_DATA_INTVL(atoi(dev_conf.data.itvl)) + 300, TIMER_ID_SEND_OLD_DATA, 0, 0, 0, 0);
                timer_queue_add(TIMEOUT_DATA_INTVL(atoi(dev_conf.data.itvl)) + CLI_APP_1S * 2, TIMER_ID_MAC_OLD_DATA, 0, 0, 0, 0);
                timer_queue_add(TIMEOUT_DATA_INTVL(atoi(dev_conf.data.itvl)) + CLI_APP_1S, TIMRT_ID_MAC_DATA, 0, 0, 0, 0);
            }
            if (update_ip == 1)
            {
                update_ip = 0;
                len = cmd_gen_mng_response(buf, BUFFER_BLOCK_SIZE, RST_SUCESS, NULL, *fcode, *type, cmdList);
            
                cli_send_to_mng(buf, len);    
            }
            else if (update_ip == 2)
            {
                update_ip = 0;
                len = cmd_gen_mng_response(buf, BUFFER_BLOCK_SIZE, RST_FAILED, "", *fcode, *type, cmdList);
    
                cli_send_to_mng(buf, len);
            }
             
            if (strcmp(dev_conf.dev.protocol, ZHONGDUN) != 0)
            {
                if ( atoi(dev_conf.dev.devtype) == TYPE_LTE || atoi(dev_conf.dev.devtype) == TYPE_GSM_LTE )
                {
                    timer_queue_add(TIMEOUT_REPORT_LOCAL_CONFIG,  TIMER_ID_REPORT_LOCAL_CONFIG, 0, 0, 0, 0);
                }
            }
		} 
		else 
		{
			cli_app_log(CLI_LOG_ERROR, "received duplicate register result message\n");
		}                                  
    } 
    else 
	{
                    
        cli_app_log(CLI_LOG_ERROR, "Register failed, cli_req:%d\n", cli_req);
    }
    
	buffer_free(buf);
    return;
}

static void handle_recv_data_from_data(I32 *deviceNumber, I32 *histData, I32 *numReceiver, I32 *funCode, I32 *deCode, I32 *cmdType, I32 *identity)
{
    I8 *buf, *buf_tmp, *msg_tmp = NULL;
    I32 buf_len, len = 0, tmp_len = 0;

    I32 cli_req, conf_req, token_req, ret_req = 0;
    I32 slot_num = 0, serialnum = 0, manual_times = 0; //it is a flag to count slot

    I32 *id = identity;
    I32 *type = cmdType; //is this cmdType
    I32 *fcode = funCode;
    I32 *dcode = deCode;
    I32 *addDevNum = deviceNumber;
    I32 *historical_data = histData;
    I32 *numRcv = numReceiver;
    UPLOADLIST *uploadList = NULL;
    if ((buf = event_queue[event_queue_e].data) == NULL || (buf_len = event_queue[event_queue_e].len) == 0) 
    {
        return;
    }

    buf[buf_len] = 0;

    cli_app_log(CLI_LOG_INFO, "rcved data packets, data is %s\n", buf);

    //check if heartbeat. will not handle at this time. fuction might be changed.
    tmp_len = cmd_check_msg_num(buf, buf_len);
    cli_app_log(CLI_LOG_INFO, "one msg Len is %d  total msg len is %d \n", tmp_len, buf_len);

    if (buf_len > tmp_len)
    {
        if ((msg_tmp = buffer_allocate()) == NULL) 
        {                        
            buffer_free(buf);
            return;
        }

        memcpy(msg_tmp, buf+tmp_len, buf_len - tmp_len);
        event_queue_add(IF_APP_EVENT_DATA_SERVER, event_queue[event_queue_e].socket, buf_len - tmp_len, msg_tmp);
    }

    cli_req = cmd_handle_mng_heartbeat_string(buf);
    if (cli_req == IF_APP_PARSE_ERROR)
    { 
        cli_app_log(CLI_LOG_WARNING, "recevice a msg which is not a json format msg\n");
        buffer_free(buf);
        return;
    }
    else if (cli_req != IF_APP_ERROR) 
    {
        cli_app_log(CLI_LOG_INFO, "MNG server, heartbeat, code is %d\n", cli_req);
            
        timer_queue_update(TIMER_ID_DATA_DEAD,TIMEOUT_SRV_DEAD(atoi(dev_conf.data.hb)));
        buffer_free(buf);
        return;
    }

    //when we recevice more than one msg from service, we recount it 
    //recevice upload cfg response 
    if (cmd_handle_upload_cfg_result(buf) == IF_APP_OK)
    {
        event_queue_add(IF_APP_EVENT_LOCAL_CONFIG, 0, 0, NULL);
        timer_queue_del(TIMER_ID_CFG_FB);
        buffer_free(buf);
        return;
    }                

    if (cmd_handle_upload_result(buf) == IF_APP_OK) 
    {   
        if (strstr(buf, "ueId") != NULL && (uploadList = RestListByUptime(cmd_get_upload_srctime(buf), DATA_TYPE_IMSI)) != NULL )
        { 
            if ( timer_queue_del(uploadList->timerId) != 0 )
            {
                cli_app_log(CLI_LOG_WARNING, "del upload timer fialed 0x%x \n", uploadList->timerId);
            }
            delDbRecord(uploadList->startId, uploadList->endId, DATA_TYPE_IMSI);
        }   
        
        uploadList = NULL;
        if ( (uploadList = RestListByUptime(cmd_get_upload_srctime(buf), DATA_TYPE_MAC)) != NULL)
        {
            if ( timer_queue_del(uploadList->timerId) != 0 )
            {
                cli_app_log(CLI_LOG_WARNING, "del upload timer fialed 0x%x \n", uploadList->timerId);
            }
            delDbRecord(uploadList->startId, uploadList->endId, DATA_TYPE_MAC);
            
        }
                      
        buffer_free(buf);
        return;
    }

    // get response from mng 
    token_req = cmd_handle_statistics_intvl(buf, numRcv);
    if (token_req != IF_APP_ERROR)
    {
        if (token_req == IF_APP_INFO_CHNG)
        { 
            I32 check_slot = 0;
            for (; slot_num < CELL_NUM; slot_num++)
            { 
                if(*(numRcv + slot_num) != 0 )
                {
                    check_slot = 1;
                    return;
                }

                slotNum[slot_num] = 0;
            } 
            
            if (check_slot == 0)
            {
               serialnum++;                              
               timer_queue_del(TIMER_ID_STATISTICS_FEEDBACK);
            } 
              
            buffer_free(buf);
            slot_num = 0;
            return;
        }
        else 
        {
            buffer_free(buf);
            return;
        }
    }

    // now check pending..... 
    if ((cmd_queue != NULL) || (cmdList.commandNum != 0)) 
    {
        //check if cmd is pending, if pending, return error. todo: might check how to doing....
        if (cmd_queue_find_status(HT_CL_STATUS_DOING) == IF_APP_OK) 
        {                            
            len = cmd_gen_mng_heartbeat_string(buf, dev_conf.dev.devNum, *addDevNum, BUFFER_BLOCK_SIZE, HT_CL_STATUS_START, NULL);
            cli_send_to_data(buf, len);
            
            len = cmd_gen_mng_response(buf, BUFFER_BLOCK_SIZE, RST_FAILED, "Another command is running.", *fcode, *type, cmdList);
            cli_send_to_data(buf, len);
        } 
        else 
        {
            //other local command is running, pending it.
            timer_queue_add(TIMEOUT_CMD_PENDING, TIMER_ID_PENDING_CMD,
                            event_queue[event_queue_e].module,
                            event_queue[event_queue_e].socket,
                            event_queue[event_queue_e].len,
                            event_queue[event_queue_e].data);
        }

        return;
    }

    if ((buf_tmp = buffer_allocate()) == NULL) 
    {                        
        buffer_free(buf);
        return;
    }

    //get manager config from buf
    cli_req = cmd_handle_mng_msg(atoi(dev_conf.dev.devtype), buf, buf_len, (I32 *) buf_tmp, fcode, type);
                          
    //management server command
    //send start.
    len = cmd_gen_mng_heartbeat_string(buf, dev_conf.dev.devNum, *addDevNum, BUFFER_BLOCK_SIZE, HT_CL_STATUS_START, NULL);
    cli_send_to_data(buf, len);
    
    if (cli_req == IF_APP_CLEAN_DATA)
    {
        recordInfo.maxId = recordInfo.minId =  recordInfo.lastId =  0;
        rmDbAndinitSqlite();
        initListGroud();
        if (atoi(dev_conf.dev.uploadMode) == 0)
        {
            timer_queue_del(TIMER_ID_UPOADLIST1);
            timer_queue_del(TIMER_ID_UPOADLIST2);
            timer_queue_del(TIMER_ID_UPOADLIST3);
            timer_queue_del(TIMER_ID_UPOADLIST4);
            timer_queue_del(TIMER_ID_UPOADLIST5);
            timer_queue_del(TIMER_ID_MAC_UPOADLIST1);
            timer_queue_del(TIMER_ID_MAC_UPOADLIST2);
            timer_queue_del(TIMER_ID_MAC_UPOADLIST3);
            timer_queue_del(TIMER_ID_MAC_UPOADLIST4);
            timer_queue_del(TIMER_ID_MAC_UPOADLIST5);
        }
    }

    if (cli_req < IF_APP_OK) 
    {    
        if (cli_req == IF_APP_ERROR)
        {
            len = cmd_gen_mng_response(buf, BUFFER_BLOCK_SIZE, RST_FAILED, "Unknown command.", *fcode, *type, cmdList); 
        }
        
        cli_send_to_data(buf, len);    
        buffer_free(buf_tmp);
        buffer_free(buf);
        return;
    }
    
    //save to local conf and xml config file.
    xml_config_overwirte(CONFIG_MODE_BACKUP);
    conf_req = xml_handle_conf(buf_tmp, cli_req);
    ret_req = cli_req;
    cli_app_log(CLI_LOG_INFO, "mng packet, conf_req is %08x\n", conf_req);
    if ((conf_req & REQUEST_UPDATA_CLI_MASK) == REQUEST_UPDATA_CLI_MASK) 
    {
#if 0
        len = cmd_gen_mng_response(buf, BUFFER_BLOCK_SIZE, RST_SUCESS, NULL, fcode, type);
        cli_send_to_tcp(event_queue[event_queue_e].socket, buf, len, 0);
#endif
        if (disable_auth == 0)
        {
            WD_AuthSDKFree();
        }

        //now destory all socket and start reconnect with new server settings.
        if (timer_queue_find(TIMER_ID_RESTART_CLI) < 0) 
        {
            cli_destroy_tcp_socket(CLI_TO_SRV_ALL_MASK);
            //start timer to re-init client.
            timer_queue_add(TIMEOUT_RESTART_CLI,
                            TIMER_ID_RESTART_CLI, 0, 0, 0, 0);
        }
        
        update_ip = 1;
    } 
    else if ((conf_req & REQUEST_UPDATA_DEV_MASK) == REQUEST_UPDATA_DEV_MASK || cmdList.commandNum > 0) 
    {

        if (cmdList.commandNum > 0)
        {
            conf_req = cmdList.commandList[cmdList.cmdIndex++].cmdId;
        }
        *id = device_handle_request(conf_req, &dev_conf, buf, (I32 *) buf_tmp, dcode);
        if (*id >= 0) 
        {
            cmd_queue_add(*fcode, event_queue[event_queue_e].socket, TIMEOUT_CMD_QUEUE, *dcode, *id, *type);
            cli_app_log(CLI_LOG_INFO, "add to command queue, decode %04x id %d\n", *dcode, *id);

            if ((*dcode == CMD_CODE_EUTRAN_START_SNIFFER) || (*dcode == CMD_CODE_EUTRAN_CONFIG_CELL) || (*dcode == CMD_LTE_DO_SNIFFER))
            {
                timer_queue_add(TIMEOUT_SNIFFER_DOING, TIMER_ID_SNIFFER_DOING,0, 0, 0, 0);
                manual_times = 0; //make sure manual sniffer times clear
            }
            else 
            {
                timer_queue_add(TIMEOUT_CMD_NO_RSP, TIMER_ID_CMD_NO_RSP, 0, 0, 0, 0);
            }

         } 
         else 
         {
            cleanCmdList();
            cli_app_log(CLI_LOG_CRITICAL, "Device interface get wrong, id:%d\n, id");
         }
    } 
    else if ((conf_req & REQUEST_SR_MASK) == REQUEST_SR_MASK) 
    {      
        if (conf_req == REQUEST_SR_GPSINFO)
        {
            for (slot_num = 0; slot_num < 7; slot_num++)
            {
                if (dev_status.bbuStatus[slot_num].bbuState == BBU_LOCATION)
                    break;
            }
            if (slot_num < 7 )
                *(I32 *)buf_tmp = ++slot_num;
            else
                *(I32 *)buf_tmp = ++slot_num;
            slot_num = 0;
        }

        *id = device_handle_request(conf_req, &dev_conf, buf, (I32 *)buf_tmp, dcode);
        if (*id >= 0) 
        {
            cmd_queue_add(*fcode, event_queue[event_queue_e].socket, TIMEOUT_CMD_QUEUE, *dcode, *id, *type);
            timer_queue_add(TIMEOUT_CMD_NO_RSP, TIMER_ID_CMD_NO_RSP, 0, 0, 0, 0);
            cli_app_log(CLI_LOG_INFO, "add to command queue, decode %04x id %d\n", *dcode, *id);
        } 
        else 
        {
            cleanCmdList();
            cli_app_log(CLI_LOG_CRITICAL, "Device interface get wrong, id:%d\n, id");
        }
    }
    else if ((conf_req & REQUEST_UPDATE_GET_DATA) == REQUEST_UPDATE_GET_DATA) 
    {
            //this code should not be used at this time, not tested and debugged.
        *id = device_handle_request(conf_req, &dev_conf, buf, (I32 *) buf_tmp, dcode);
       
        cmd_queue_add(0, 0, TIMEOUT_CMD_QUEUE, *dcode, *id, *type);
        if (conf_req == REQUEST_UPDATE_GET_DATA)
        {
            *historical_data = 1;
            historical_time[0] = *(I32 *)buf_tmp;
            historical_time[1] = *((I32 *)buf_tmp + 1);
        }
        
        len = cmd_gen_mng_response(buf, BUFFER_BLOCK_SIZE, RST_SUCESS, NULL, *fcode, *type, cmdList);
        cli_send_to_mng(buf, len);
    } 
    else if ((conf_req & REQUEST_UPDATA_IF_APP) == REQUEST_UPDATA_IF_APP) 
    {
        if ( conf_req == REQUEST_UPDATA_TAC_CYCLE)
        {
            timer_queue_del(TIMER_ID_CHNG_TAC_CYCLE);
            if (atoi(dev_conf.capLte.tac_cycle) >= 0)
                timer_queue_add(TIMEOUT_CHNG_TAC_CYCLE(atoi(dev_conf.capLte.tac_cycle)), TIMER_ID_CHNG_TAC_CYCLE, 0, 0, 0, 0);
        }
        len = cmd_gen_mng_response(buf, BUFFER_BLOCK_SIZE, RST_SUCESS, NULL, *fcode, *type, cmdList);
        cli_send_to_data(buf, len);
    } 
    else if ((conf_req & REQUEST_SR_LOCAL_MASK) == REQUEST_SR_LOCAL_MASK )
    {     
        if (conf_req == SEARCH_ONE_RECORD)
        {
            ZHONGDUNDATA searchRecord;
            searchRecord.seqNum = 0;
            if (findOneRecord(true,  *((SEARCHRECORD *)buf_tmp), &searchRecord))
            {   
                len = packSearchOneRecord(false, buf, searchRecord, (*((SEARCHRECORD *)buf_tmp)).seqNum);
                cli_send_to_tcp(event_queue[event_queue_e].socket, buf, len, 0);             
            }
            else
            {   
                len = packSearchOneRecord(false, buf, searchRecord, (*((SEARCHRECORD *)buf_tmp)).seqNum);
                cli_send_to_tcp(event_queue[event_queue_e].socket, buf, len, 0);               
            }
               
            
        }
        else if (conf_req == REQUEST_SR_50_DAY_RECORD)
        {
            ZHONGDUN_DB_LIST dbList;
            search50DayRecord(false, &dbList);
            len = packHistoryInformationAck(buf, dbList);
            cli_send_to_tcp(event_queue[event_queue_e].socket, buf, len, 0);  
        }
        else if (conf_req == REQUEST_SR_ONE_DAY_RECORD)
        {

            I32 Filesize = refRecordSize(false, buf_tmp);
            len = packOneDayRecordAck(buf, Filesize);
            cli_send_to_tcp(event_queue[event_queue_e].socket, buf, len, 0);  

        }
        else if (conf_req == REQUEST_SR_RECORD_BY_SEQ)
        {
            setSendRecordSn(false, *(U16 *)buf_tmp);
            timer_queue_del(TIMER_ID_UNICOM_SN_RECORD);
            timer_queue_add(CLI_APP_1S * 2, TIMER_ID_UNICOM_SN_RECORD, 0, 0, 0, 0);
        }
        else if (conf_req == REQUEST_SR_RECORD_END)
        {
            timer_queue_del(TIMER_ID_UNICOM_SN_RECORD);
        }
        else if (conf_req == REQUEST_CLEAN_FEP_DATA)
        {
            cleanDataByModel(true);
            len = packsuccssAck(buf);
            cli_send_to_tcp(event_queue[event_queue_e].socket, buf, len, 0); 
        }
        else if (conf_req == REQUEST_SEND_UPGRADE_PACKET)
        {
            len = packUpgradePacket(*((ZHONGDUN_PACKET *)buf_tmp), buf);
            cli_send_to_tcp(event_queue[event_queue_e].socket, buf, len, 0); 
        }
        else
        {
            len = cmd_gen_sr_local_response(conf_req, buf, buf_tmp, &dev_conf);

            cli_send_to_data(buf, len);
        }
    }
    else 
    {
         cli_app_log(CLI_LOG_CRITICAL, "ERROR: should not be here\n");
    }

    buffer_free(buf_tmp);
    buffer_free(buf);
    return;
}


void handle_recv_data_from_mng(I32 *deviceNumber, I32 *histData, I32 *numReceiver, I32 *funCode, I32 *deCode, I32 *cmdType, I32 *identity)
{
    I8 *buf, *buf_tmp, *msg_tmp = NULL;
    I32 buf_len, len = 0, tmp_len = 0;

    I32 cli_req, conf_req, token_req, ret_req = 0;
    I32 slot_num = 0, serialnum = 0, manual_times = 0; //it is a flag to count slot

    I32 *id = identity;
    I32 *type = cmdType; //is this cmdType
    I32 *fcode = funCode;
    I32 *dcode = deCode;
    I32 *addDevNum = deviceNumber;
    I32 *historical_data = histData;
    I32 *numRcv = numReceiver;
    UPLOADLIST *uploadList = NULL;
    if ((buf = event_queue[event_queue_e].data) == NULL || (buf_len = event_queue[event_queue_e].len) == 0) 
    {
        return;
    }

    buf[buf_len] = 0;

    cli_app_log(CLI_LOG_INFO, "rcved mng packets, data is %s\n", buf);

    //check if heartbeat. will not handle at this time. fuction might be changed.
    tmp_len = cmd_check_msg_num(buf, buf_len);
    cli_app_log(CLI_LOG_INFO, "one msg Len is %d  total msg len is %d \n", tmp_len, buf_len);

    if (buf_len > tmp_len)
    {
        if ((msg_tmp = buffer_allocate()) == NULL) 
        {                        
            buffer_free(buf);
            return;
        }

        memcpy(msg_tmp, buf+tmp_len, buf_len - tmp_len);
        event_queue_add(IF_APP_EVENT_MNG_SERVER, event_queue[event_queue_e].socket, buf_len - tmp_len, msg_tmp);
    }

    cli_req = cmd_handle_mng_heartbeat_string(buf);
    if (cli_req == IF_APP_PARSE_ERROR)
    { 
        cli_app_log(CLI_LOG_WARNING, "recevice a msg which is not a json format msg\n");
        buffer_free(buf);
        return;
    }
    else if (cli_req != IF_APP_ERROR) 
    {
        cli_app_log(CLI_LOG_INFO, "MNG server, heartbeat, code is %d\n", cli_req);
            
        timer_queue_update(TIMER_ID_MNG_DEAD,TIMEOUT_SRV_DEAD(atoi(dev_conf.mng.hb)));
        buffer_free(buf);
        return;
    }

    //when we recevice more than one msg from service, we recount it 
    //recevice upload cfg response 
    if (cmd_handle_upload_cfg_result(buf) == IF_APP_OK)
    {
        event_queue_add(IF_APP_EVENT_LOCAL_CONFIG, 0, 0, NULL);
        timer_queue_del(TIMER_ID_CFG_FB);
        buffer_free(buf);
        return;
    }                

    if (cmd_handle_upload_result(buf) == IF_APP_OK) 
    {   
        if (strstr(buf, "ueId") != NULL && (uploadList = RestListByUptime(cmd_get_upload_srctime(buf), DATA_TYPE_IMSI)) != NULL )
        { 
            if ( timer_queue_del(uploadList->timerId) != 0 )
            {
                cli_app_log(CLI_LOG_WARNING, "del upload timer fialed 0x%x \n", uploadList->timerId);
            }
            delDbRecord(uploadList->startId, uploadList->endId, DATA_TYPE_IMSI);
        }                 
        buffer_free(buf);
        return;
    }

    // get response from mng 
    token_req = cmd_handle_statistics_intvl(buf, numRcv);
    if (token_req != IF_APP_ERROR)
    {
        if (token_req == IF_APP_INFO_CHNG)
        { 
            I32 check_slot = 0;
            for (; slot_num < CELL_NUM; slot_num++)
            { 
                if(*(numRcv + slot_num) != 0 )
                {
                    check_slot = 1;
                    return;
                }

                slotNum[slot_num] = 0;
            } 
            
            if (check_slot == 0)
            {
               serialnum++;                              
               timer_queue_del(TIMER_ID_STATISTICS_FEEDBACK);
            } 
              
            buffer_free(buf);
            slot_num = 0;
            return;
        }
        else 
        {
            buffer_free(buf);
            return;
        }
    }

    // now check pending..... 
    if (((cmd_queue != NULL) || (cmdList.commandNum != 0)) && (cmd_check_is_rebootCmd(buf) != IF_APP_OK) ) 
    {
        //check if cmd is pending, if pending, return error. todo: might check how to doing....
        if (cmd_queue_find_status(HT_CL_STATUS_DOING) == IF_APP_OK) 
        {                            
            len = cmd_gen_mng_heartbeat_string(buf, dev_conf.dev.devNum, *addDevNum, BUFFER_BLOCK_SIZE, HT_CL_STATUS_START, NULL);
            cli_send_to_mng(buf, len);
            
            len = cmd_gen_mng_response(buf, BUFFER_BLOCK_SIZE, RST_FAILED, "Another command is running.", *fcode, *type, cmdList);
            cli_send_to_mng(buf, len);
        } 
        else 
        {
            //other local command is running, pending it.
            timer_queue_add(TIMEOUT_CMD_PENDING, TIMER_ID_PENDING_CMD,
                            event_queue[event_queue_e].module,
                            event_queue[event_queue_e].socket,
                            event_queue[event_queue_e].len,
                            event_queue[event_queue_e].data);
        }

        return;
    }

    if ((buf_tmp = buffer_allocate()) == NULL) 
    {                        
        buffer_free(buf);
        return;
    }

    //get manager config from buf
    cli_req = cmd_handle_mng_msg(atoi(dev_conf.dev.devtype), buf, buf_len, (I32 *) buf_tmp, fcode, type);
                          
    //management server command
    //send start.
    len = cmd_gen_mng_heartbeat_string(buf, dev_conf.dev.devNum, *addDevNum, BUFFER_BLOCK_SIZE, HT_CL_STATUS_START, NULL);
    cli_send_to_mng(buf, len);
    
    if (cli_req == IF_APP_CLEAN_DATA)
    {
        recordInfo.maxId = recordInfo.minId =  recordInfo.lastId =  0;
        rmDbAndinitSqlite();
        initListGroud();
        if (atoi(dev_conf.dev.uploadMode) == 0)
        {
            timer_queue_del(TIMER_ID_UPOADLIST1);
            timer_queue_del(TIMER_ID_UPOADLIST2);
            timer_queue_del(TIMER_ID_UPOADLIST3);
            timer_queue_del(TIMER_ID_UPOADLIST4);
            timer_queue_del(TIMER_ID_UPOADLIST5);
            timer_queue_del(TIMER_ID_MAC_UPOADLIST1);
            timer_queue_del(TIMER_ID_MAC_UPOADLIST2);
            timer_queue_del(TIMER_ID_MAC_UPOADLIST3);
            timer_queue_del(TIMER_ID_MAC_UPOADLIST4);
            timer_queue_del(TIMER_ID_MAC_UPOADLIST5);
        }
    }

    if (cli_req < IF_APP_OK) 
    {    
        if (cli_req == IF_APP_ERROR)
        {
            len = cmd_gen_mng_response(buf, BUFFER_BLOCK_SIZE, RST_FAILED, "Unknown command.", *fcode, *type, cmdList); 
        }
        
        cli_send_to_mng(buf, len);    
        buffer_free(buf_tmp);
        buffer_free(buf);
        return;
    }
    
    //save to local conf and xml config file.
    xml_config_overwirte(CONFIG_MODE_BACKUP);
    conf_req = xml_handle_conf(buf_tmp, cli_req);
    ret_req = cli_req;
    cli_app_log(CLI_LOG_INFO, "mng packet, conf_req is %08x\n", conf_req);
    if ((conf_req & REQUEST_UPDATA_CLI_MASK) == REQUEST_UPDATA_CLI_MASK) 
    {
#if 0
        len = cmd_gen_mng_response(buf, BUFFER_BLOCK_SIZE, RST_SUCESS, NULL, fcode, type);
        cli_send_to_tcp(event_queue[event_queue_e].socket, buf, len, 0);
#endif
        if (disable_auth == 0)
        {
            WD_AuthSDKFree();
        }

        //now destory all socket and start reconnect with new server settings.
        if (timer_queue_find(TIMER_ID_RESTART_CLI) < 0) 
        {
            cli_destroy_tcp_socket(CLI_TO_SRV_ALL_MASK);
            //start timer to re-init client.
            timer_queue_add(TIMEOUT_RESTART_CLI,
                            TIMER_ID_RESTART_CLI, 0, 0, 0, 0);
        }
        
        update_ip = 1;
    } 
    else if ((conf_req & REQUEST_UPDATA_DEV_MASK) == REQUEST_UPDATA_DEV_MASK || cmdList.commandNum > 0) 
    {
        if (strcmp(dev_conf.dev.protocol, LOCATION) == 0)
        {
            handle_location_status(conf_req);
        }

        if (cmdList.commandNum > 0)
        {
            conf_req = cmdList.commandList[cmdList.cmdIndex++].cmdId;
        }
        *id = device_handle_request(conf_req, &dev_conf, buf, (I32 *) buf_tmp, dcode);
        if (*id >= 0) 
        {
            cmd_queue_add(*fcode, event_queue[event_queue_e].socket, TIMEOUT_CMD_QUEUE, *dcode, *id, *type);
            cli_app_log(CLI_LOG_INFO, "add to command queue, decode %04x id %d\n", *dcode, *id);

            if ((*dcode == CMD_CODE_EUTRAN_START_SNIFFER) || (*dcode == CMD_CODE_EUTRAN_CONFIG_CELL) || (*dcode == CMD_LTE_DO_SNIFFER))
            {
                timer_queue_add(TIMEOUT_SNIFFER_DOING, TIMER_ID_SNIFFER_DOING,0, 0, 0, 0);
                manual_times = 0; //make sure manual sniffer times clear
            }
            else 
            {
                timer_queue_add(TIMEOUT_CMD_NO_RSP, TIMER_ID_CMD_NO_RSP, 0, 0, 0, 0);
            }
         } 
         else 
         {
            cleanCmdList();
            cli_app_log(CLI_LOG_CRITICAL, "Device interface get wrong, id:%d\n, id");
         }
    } 
    else if ((conf_req & REQUEST_SR_MASK) == REQUEST_SR_MASK) 
    {      
        if (conf_req == REQUEST_SR_GPSINFO)
        {
            for (slot_num = 0; slot_num < 7; slot_num++)
            {
                if (dev_status.bbuStatus[slot_num].bbuState == BBU_LOCATION)
                    break;
            }
            if (slot_num < 7 )
                *(I32 *)buf_tmp = ++slot_num;
            else
                *(I32 *)buf_tmp = ++slot_num;
            slot_num = 0;
        }

        *id = device_handle_request(conf_req, &dev_conf, buf, (I32 *)buf_tmp, dcode);
        if (*id >= 0) 
        {
            cmd_queue_add(*fcode, event_queue[event_queue_e].socket, TIMEOUT_CMD_QUEUE, *dcode, *id, *type);
            timer_queue_add(TIMEOUT_CMD_NO_RSP, TIMER_ID_CMD_NO_RSP, 0, 0, 0, 0);
            cli_app_log(CLI_LOG_INFO, "add to command queue, decode %04x id %d\n", *dcode, *id);
        } 
        else 
        {
            cleanCmdList();
            cli_app_log(CLI_LOG_CRITICAL, "Device interface get wrong, id:%d\n, id");
        }
    }
    else if ((conf_req & REQUEST_UPDATE_GET_DATA) == REQUEST_UPDATE_GET_DATA) 
    {
            //this code should not be used at this time, not tested and debugged.
        *id = device_handle_request(conf_req, &dev_conf, buf, (I32 *) buf_tmp, dcode);
       
        cmd_queue_add(0, 0, TIMEOUT_CMD_QUEUE, *dcode, *id, *type);
        if (conf_req == REQUEST_UPDATE_GET_DATA)
        {
            *historical_data = 1;
            historical_time[0] = *(I32 *)buf_tmp;
            historical_time[1] = *((I32 *)buf_tmp + 1);
        }
        
        len = cmd_gen_mng_response(buf, BUFFER_BLOCK_SIZE, RST_SUCESS, NULL, *fcode, *type, cmdList);
        cli_send_to_mng(buf, len);
    } 
    else if ((conf_req & REQUEST_UPDATA_IF_APP) == REQUEST_UPDATA_IF_APP) 
    {
        if ( conf_req == REQUEST_UPDATA_TAC_CYCLE)
        {
            timer_queue_del(TIMER_ID_CHNG_TAC_CYCLE);
            if (atoi(dev_conf.capLte.tac_cycle) >= 0)
                timer_queue_add(TIMEOUT_CHNG_TAC_CYCLE(atoi(dev_conf.capLte.tac_cycle)), TIMER_ID_CHNG_TAC_CYCLE, 0, 0, 0, 0);
        }
        len = cmd_gen_mng_response(buf, BUFFER_BLOCK_SIZE, RST_SUCESS, NULL, *fcode, *type, cmdList);
        cli_send_to_mng(buf, len);
    } 
    else if ((conf_req & REQUEST_SR_LOCAL_MASK) == REQUEST_SR_LOCAL_MASK )
    {    
        if (conf_req == SEARCH_ONE_RECORD)
        {
            ZHONGDUNDATA searchRecord;
            searchRecord.seqNum = 0;
            if (findOneRecord(true,  *((SEARCHRECORD *)buf_tmp), &searchRecord))
            {   
                len = packSearchOneRecord(true, buf, searchRecord, (*((SEARCHRECORD *)buf_tmp)).seqNum);
                cli_send_to_tcp(event_queue[event_queue_e].socket, buf, len, 0);             
            }
            else
            {   
                len = packSearchOneRecord(true, buf, searchRecord, (*((SEARCHRECORD *)buf_tmp)).seqNum);
                cli_send_to_tcp(event_queue[event_queue_e].socket, buf, len, 0);               
            }
               
            
        }
        else if (conf_req == REQUEST_SR_50_DAY_RECORD)
        {
            ZHONGDUN_DB_LIST dbList;
            search50DayRecord(true, &dbList);
            len = packHistoryInformationAck(buf, dbList);
            cli_send_to_tcp(event_queue[event_queue_e].socket, buf, len, 0);  
        }
        else if (conf_req == REQUEST_SR_ONE_DAY_RECORD)
        {

            I32 Filesize = refRecordSize(true, buf_tmp);
            len = packOneDayRecordAck(buf, Filesize);
            cli_send_to_tcp(event_queue[event_queue_e].socket, buf, len, 0);  

        }
        else if (conf_req == REQUEST_SR_RECORD_BY_SEQ)
        {
            setSendRecordSn(true, *(U16 *)buf_tmp);
            timer_queue_del(TIMER_ID_MOBILE_SN_RECORD);
            timer_queue_add(CLI_APP_1S * 2, TIMER_ID_MOBILE_SN_RECORD, 0, 0, 0, 0);
        }
        else if (conf_req == REQUEST_SR_RECORD_END)
        {
            timer_queue_del(TIMER_ID_MOBILE_SN_RECORD);
        }
        else if (conf_req == REQUEST_CLEAN_FEP_DATA)
        {
            cleanDataByModel(true);
            len = packsuccssAck(buf);
            cli_send_to_tcp(event_queue[event_queue_e].socket, buf, len, 0); 
        }
        else if (conf_req == REQUEST_SEND_UPGRADE_PACKET)
        {
            len = packUpgradePacket(*((ZHONGDUN_PACKET *)buf_tmp), buf);
            cli_send_to_tcp(event_queue[event_queue_e].socket, buf, len, 0); 
        }
        else if (conf_req == REQUEST_SR_DEVICE_USAGE)
        {

            U32 startTm = 0, currentTm = 0, endTm = 0;
            while(cmd_gen_device_usage(&currentTm, &startTm, &endTm, &len, buf, buf_tmp) == IF_APP_OK)
            {
                cli_send_to_mng(buf, len);
            }
            cli_send_to_mng(buf, len);
        }
        else if (conf_req == REQUEST_SR_LOCATION_STATUS)
        {
            len = cmd_gen_location_status(&dev_status, buf, &dev_conf);
            cli_send_to_mng(buf, len);

        }
        else
        {
            len = cmd_gen_sr_local_response(conf_req, buf, buf_tmp, &dev_conf);
    
            cli_send_to_mng(buf, len);
        }
    }
    else 
    {
         cli_app_log(CLI_LOG_CRITICAL, "ERROR: should not be here\n");
    }

    buffer_free(buf_tmp);
    buffer_free(buf);
    return;
}

void handle_cli_internal_timer(I32 *deviceNumber, I32 *histData, I32 *sock, I32 *rstTime, I32 *numReceive, 
                               I32 *funcode, I32 *deCode, I32 *cmdType, I32 *identity)
{
    I8 *buf, *buf_tmp = NULL;
    I32 buf_len = 0, len = 0;
    I32 slot_num = 0;  
    I32 serialnum = 0; 
    I32 currentSlot = 0, config_slot = 0, updateSlot = 0;    
    I32 *id = identity;
    I32 *type = cmdType;
    I32 *dcode = deCode;
    I32 *fcode = funcode;
    I32 *addDevNum = deviceNumber;
    I32 *historical_data = histData;
    I32 *socket = sock;
    I32 *numRcv = numReceive;
    I32 *cli_rst_times = rstTime;
    UPLOADLIST *uploadList = NULL;
    if ((buf_tmp = buffer_allocate()) == NULL) 
    {
        return;
    }
    
    switch (event_queue[event_queue_e].socket) 
    {
        case TIMER_ID_GET_STATUS:
            if (cmd_queue == NULL || cmd_queue_find_status(HT_CL_STATUS_DOING) == IF_APP_OK) 
            {
                //len and buf_len just for test to check code.
                len = device_handle_request(REQUEST_GET_STATUS, &dev_conf, buf_tmp, NULL, &buf_len);
                //restart timer.                            
                timer_queue_add(TIMEOUT_GET_STATUS(atoi(dev_conf.mng.itvl)), TIMER_ID_GET_STATUS, 0, 0, 0,0);

            } 
            else 
            {
                 timer_queue_add(TIMEOUT_CMD_PENDING, TIMER_ID_GET_STATUS, 0, 0, 0, 0);
            }

            break;
        case TIMER_ID_DEV_DEAD:
            cli_app_log(CLI_LOG_CRITICAL,  "///////////////////////Warning: device side dead...//////////////////\n");
            
            //send warning to device manager.
            len = cmd_gen_warning(WR_DEV_RESTART, buf_tmp, "Device manager is dead");
            cli_send_to_mng(buf_tmp, len);
            createRestartCauseFileByCode(SYSTEM_SOFT_RESTART);
            saveImportantLog("bes process lost connection so reboot");
            while (restart_time) 
            {
                restart_time--;
                sleep(1);
            }

            if (disable_auth == 0)
                WD_AuthSDKFree();
#ifndef MODULE_TEST
            fflush(log);
            system("reboot -f");
#endif            
            break;

       case TIMER_ID_UPGREAD_FAILED:
           cli_app_log(CLI_LOG_ERROR, "down pkg failed .\n");
           system("killall fwm.sh");
           //TODO report upgrade failed message to server
           //system("reboot");
           break;

       case TIMER_ID_MNG_HEART_BEAT:
           if (cli_get_mng_status() == MNG_SERVER_STATUS_CONNECTED) 
           {
               if (cmd_queue_find_status(HT_CL_STATUS_DOING) == IF_APP_OK) 
               {
                   len = cmd_gen_mng_heartbeat_string(buf_tmp, dev_conf.dev.devNum, *addDevNum, BUFFER_BLOCK_SIZE, HT_CL_STATUS_DOING, NULL);
               }
               else 
               {
                   len = cmd_gen_mng_heartbeat_string(buf_tmp, dev_conf.dev.devNum, *addDevNum, BUFFER_BLOCK_SIZE, devStatus, NULL);
               }
           
               cli_send_to_mng(buf_tmp, len);
               if (cli_get_data_status() == DATA_SERVER_STATUS_CONNECTED)
               {
                   if (strcmp(dev_conf.dev.protocol, CAIPIN) == 0 || strcmp(dev_conf.dev.protocol, ZHIHUI) == 0 
                       || strcmp(dev_conf.dev.protocol, KUANGUANG) == 0 || strcmp(dev_conf.dev.protocol, CAIPINNEW) == 0 
                       || strcmp(dev_conf.dev.protocol, HUANSHUO) == 0 || strcmp(dev_conf.dev.protocol, WANGXUN) == 0
                       || strcmp(dev_conf.dev.protocol, FENGHUO) == 0 || strcmp(dev_conf.dev.protocol, RENZIXING) == 0
                       || strcmp(dev_conf.dev.protocol, JINFENG) == 0 || strcmp(dev_conf.dev.protocol, GAOKE) == 0
                       || strcmp(dev_conf.dev.protocol, BAIZHUO) == 0 || strcmp(dev_conf.dev.protocol, LOCATION) == 0
                       || strcmp(dev_conf.dev.protocol, ZISHUO) == 0)
                   {
                       cli_send_to_data(buf_tmp, len);
                   }
               }
               timer_queue_add(TIMEOUT_MNG_INTVL(atoi(dev_conf.mng.hb)), TIMER_ID_MNG_HEART_BEAT, 0, 0, 0, 0);
           }

           break;

        case TIMER_ID_SEND_OLD_DATA:
            if (cli_get_data_status() == DATA_SERVER_STATUS_CONNECTED) 
            {                
                //if command is running, pending 1s
                if ((cmd_queue != NULL) || (cmdList.commandNum != 0)) 
                {
                    timer_queue_add(CLI_APP_1S, event_queue[event_queue_e].socket, 0, 0, 0, 0);
                    break;
                }
                if ( atoi(dev_conf.data.enable) == 1 && recordInfo.maxId > 0 && recordInfo.maxId <= recordInfo.lastId  )
                {
                    recordInfo.realNum = 0;
                    uploadList = oldDataGetNotUseList(DATA_TYPE_IMSI);
                    if ( uploadList == NULL )
                    { 
                        cli_app_log(CLI_LOG_WARNING, "all old list are using \n");
                    }
                    else
                    {     
                        recordInfo.oldId = recordInfo.minId;                   
                        getDbRecord(true, &recordInfo, &uploadList->startId, &uploadList->endId, false);  
                    }
                    if ( recordInfo.realNum > 0 )
                    {
                        uploadList->isWaittingRsp = true;
                        uploadList->isOldData = true;
                         
                        setListUptime(&recordInfo.phoneInfoBuf[0].uptime, &uploadList->uptime, DATA_TYPE_IMSI);
                        if (strcmp(dev_conf.dev.protocol, CAIPIN) == 0 || strcmp(dev_conf.dev.protocol, ZHIHUI) == 0
                            || strcmp(dev_conf.dev.protocol, CAIPINNEW) == 0 ||  strcmp(dev_conf.dev.protocol, KUANGUANG) == 0
                            || strcmp(dev_conf.dev.protocol, HUANSHUO) == 0 || strcmp(dev_conf.dev.protocol, WANGXUN) == 0
                            || strcmp(dev_conf.dev.protocol, FENGHUO) == 0  || strcmp(dev_conf.dev.protocol, RENZIXING) == 0
                            || strcmp(dev_conf.dev.protocol, JINFENG) == 0 || strcmp(dev_conf.dev.protocol, NANFEI) == 0
                             || strcmp(dev_conf.dev.protocol, GAOKE) == 0 || strcmp(dev_conf.dev.protocol, LOCATION) == 0
                             || strcmp(dev_conf.dev.protocol, ZISHUO) == 0)

                        {
                            len = cmd_up_current_data(upCurrentData, &recordInfo);
                            cli_send_to_data(upCurrentData, len);
                        }
                        else if (strcmp(dev_conf.dev.protocol, LEGU) == 0)
                        {
                            send_imsi_data(true, (I8*)&recordInfo, upCurrentData);
                        }
                        timer_queue_add(TIMEOUT_RESTART_SEND_DATA,
                                uploadList->timerId, 0, 0, 0, 0);
                        if (strcmp(dev_conf.dev.protocol, NANFEI) == 0 || strcmp(dev_conf.dev.protocol, LEGU) == 0)
                        {
                            RestListByUptime(uploadList->uptime, DATA_TYPE_IMSI);
                            if ( timer_queue_del(uploadList->timerId) != 0 )
                            {
                                cli_app_log(CLI_LOG_WARNING, "del upload timer fialed 0x%x \n", uploadList->timerId);
                            }
                            delDbRecord(uploadList->startId, uploadList->endId, DATA_TYPE_IMSI);
                        }
                    }
                    if ( recordInfo.maxId <= recordInfo.minId && noUsingList(DATA_TYPE_IMSI) && macRecordInfo.maxId == 0)
                    {
                        recordInfo.maxId = recordInfo.minId =  recordInfo.lastId =  0;
                        rmDbAndinitSqlite();
                        cli_app_log(CLI_LOG_INFO, "clean all data in database and rm this database \n");

                    }
                }
                timer_queue_add(TIMEOUT_DATA_INTVL(atoi(dev_conf.data.itvl)) + 300, TIMER_ID_SEND_OLD_DATA, 0, 0, 0, 0);
            }
            break;       

        case TIMER_ID_DATA_HEART_BEAT:
            if (cli_get_data_status() == DATA_SERVER_STATUS_CONNECTED) 
            {    
                if (strcmp(dev_conf.dev.protocol, ZHONGDUN) == 0)
                {
                    len = cmd_gen_mng_heartbeat_string(buf_tmp, dev_conf.dev.devNum, *addDevNum, BUFFER_BLOCK_SIZE, devStatus, NULL);
                    cli_send_to_data(buf_tmp, len);

                }
                else
                {

                    //if command is running, pending 1s
                    if ((cmd_queue != NULL) || (cmdList.commandNum != 0)) 
                    {
                        timer_queue_add(CLI_APP_1S, event_queue[event_queue_e].socket, 0, 0, 0, 0);
                        break;
                    }

                    if ((atoi(dev_conf.data.enable) == 1) && (*historical_data == 0)) 
                    {
                        if ( recordInfo.maxId > recordInfo.lastId )
                        {
                            recordInfo.realNum = 0;
                            uploadList = getNotUsedList(DATA_TYPE_IMSI);
                            if ( uploadList == NULL )
                            { 
                                cli_app_log(CLI_LOG_WARNING, "all list are using \n");
                            }
                            else
                            {                            
                                getDbRecord(false, &recordInfo, &uploadList->startId, &uploadList->endId, false);

                            }
                            if ( recordInfo.realNum > 0 )
                            {
                                uploadList->isWaittingRsp = true;
                                setListUptime(&recordInfo.phoneInfoBuf[0].uptime, &uploadList->uptime, DATA_TYPE_IMSI);
                                if (strcmp(dev_conf.dev.protocol, CAIPIN) == 0 || strcmp(dev_conf.dev.protocol, ZHIHUI) == 0
                                        || strcmp(dev_conf.dev.protocol, CAIPINNEW) == 0 ||  strcmp(dev_conf.dev.protocol, KUANGUANG) == 0
                                        || strcmp(dev_conf.dev.protocol, HUANSHUO) == 0 || strcmp(dev_conf.dev.protocol, WANGXUN) == 0
                                        || strcmp(dev_conf.dev.protocol, FENGHUO) == 0  || strcmp(dev_conf.dev.protocol, RENZIXING) == 0
                                        || strcmp(dev_conf.dev.protocol, JINFENG) == 0 || strcmp(dev_conf.dev.protocol, NANFEI) == 0
                                         || strcmp(dev_conf.dev.protocol, GAOKE) == 0 || strcmp(dev_conf.dev.protocol, LOCATION) == 0
                                         || strcmp(dev_conf.dev.protocol, ZISHUO) == 0)

                                {
                                    len = cmd_up_current_data(upCurrentData, &recordInfo);
                                    cli_send_to_data(upCurrentData, len);
                                }
                                else if (strcmp(dev_conf.dev.protocol, LEGU) == 0)
                                {
                                    send_imsi_data(true, (I8 *)&recordInfo, upCurrentData);

                                }
                                else
                                {
                                    len = cmd_up_current_data(upCurrentData, &recordInfo);
                                    cli_send_to_data(upCurrentData, len);
                                    cli_app_log(CLI_LOG_INFO, "send imsi to server len is %d \n", len);
                                }
                                timer_queue_add(TIMEOUT_RESTART_SEND_DATA,
                                        uploadList->timerId, 0, 0, 0, 0);
                                if (strcmp(dev_conf.dev.protocol, ZHONGDUN) == 0 || strcmp(dev_conf.dev.protocol, NANFEI) == 0 
                                    || strcmp(dev_conf.dev.protocol, LEGU) == 0)
                                {
                                    RestListByUptime(uploadList->uptime, DATA_TYPE_IMSI);
                                    if ( timer_queue_del(uploadList->timerId) != 0 )
                                    {
                                        cli_app_log(CLI_LOG_WARNING, "del upload timer fialed 0x%x \n", uploadList->timerId);
                                    }
                                    delDbRecord(uploadList->startId, uploadList->endId, DATA_TYPE_IMSI);
                                }
                            }
                        }

                    }
                    else if (*historical_data == 1)
                    {
                        cli_app_log(CLI_LOG_DEFAULT, "-------send historical data to service-------dat3== %d   %d \n", historical_time[0], historical_time[1]);

                        *id = device_handle_request(REQUEST_UPDATE_GET_DATA, &dev_conf, buf_tmp, (I32 *) historical_time, dcode);
                        cmd_queue_add(0, 0, TIMEOUT_CMD_QUEUE, *dcode, *id, 0);
                    }
                }
                //restart timer.
                if (strcmp(dev_conf.dev.protocol, ZHONGDUN) != 0)
                    timer_queue_add(TIMEOUT_DATA_INTVL(atoi(dev_conf.data.itvl)), TIMER_ID_DATA_HEART_BEAT, 0, 0, 0, 0);
                else
                    timer_queue_add(TIMEOUT_MNG_INTVL(atoi(dev_conf.data.hb)), TIMER_ID_DATA_HEART_BEAT, 0, 0, 0, 0);

            }
            break;

        case TIMER_ID_UPOADLIST1:
        case TIMER_ID_UPOADLIST2:
        case TIMER_ID_UPOADLIST3:
        case TIMER_ID_UPOADLIST4:
        case TIMER_ID_UPOADLIST5:
            if (cli_get_data_status() == DATA_SERVER_STATUS_CONNECTED) 
            {
                uploadList = searchListByTimeId(event_queue[event_queue_e].socket, DATA_TYPE_IMSI);
                
                if ( uploadList != NULL )
                {
                    recordInfo.realNum = 0;
                    cli_app_log(CLI_LOG_NOTICE, "resend data timerId is 0x%x, startId is %d endId is %d \n", event_queue[event_queue_e].socket, 
                               uploadList->startId, uploadList->endId);
                    getUploadFailedRecord(&recordInfo, uploadList->startId, uploadList->endId);
                    if ( recordInfo.realNum > 0 )
                    {
                        if (strcmp(dev_conf.dev.protocol, CAIPIN) == 0 || strcmp(dev_conf.dev.protocol, ZHIHUI) == 0
                           || strcmp(dev_conf.dev.protocol, CAIPINNEW) == 0  ||  strcmp(dev_conf.dev.protocol, KUANGUANG) == 0  
                           || strcmp(dev_conf.dev.protocol, HUANSHUO) == 0 || strcmp(dev_conf.dev.protocol, WANGXUN) == 0
                           || strcmp(dev_conf.dev.protocol, FENGHUO) == 0 || strcmp(dev_conf.dev.protocol, LOCATION) == 0)
                        {
                             len = cmd_up_current_data(upCurrentData, &recordInfo);
                             cli_send_to_data(upCurrentData, len);
                        }
                        else if (strcmp(dev_conf.dev.protocol, LEGU) == 0)
                        {
                            send_imsi_data(true, (I8 *)&recordInfo, upCurrentData);
                        }
                        else
                        {
                            len = cmd_up_current_data(upCurrentData, &recordInfo);
                            cli_send_to_data(upCurrentData, len);
                            cli_app_log(CLI_LOG_INFO, "send imsi to server len is %d \n", len);
                        }
                        timer_queue_add(TIMEOUT_RESTART_SEND_DATA,
                                event_queue[event_queue_e].socket, 0, 0, 0, 0); 
                    }
                    else
                    {
                        uploadList->isWaittingRsp = false;
                        uploadList->isOldData = false;
                    }
                }

            }
            break;

        case TIMRT_ID_MAC_DATA:
            if (cli_get_data_status() == DATA_SERVER_STATUS_CONNECTED) 
            {                
                //if command is running, pending 1s
                if ((cmd_queue != NULL) || (cmdList.commandNum != 0)) 
                {
                    timer_queue_add(CLI_APP_1S, event_queue[event_queue_e].socket, 0, 0, 0, 0);
                    break;
                }

                if ((atoi(dev_conf.data.enable) == 1) ) 
                {
                    if ( macRecordInfo.maxId > macRecordInfo.lastId )
                    {
                        macRecordInfo.realNum = 0;
                        uploadList = getNotUsedList(DATA_TYPE_MAC);
                        if ( uploadList == NULL )
                        { 
                            cli_app_log(CLI_LOG_WARNING, "all list are using \n");
                        }
                        else
                        {                            
                            getDbMacRecord(false, &macRecordInfo, &uploadList->startId, &uploadList->endId, false);

                        }
                        if ( macRecordInfo.realNum > 0 )
                        {
                            uploadList->isWaittingRsp = true;
                            setListUptime(&macRecordInfo.macInfoBuf[0].uptime, &uploadList->uptime, DATA_TYPE_MAC);
                            cli_app_log(CLI_LOG_INFO, "upmac time id is %d, uptime is %d \n", uploadList->timerId, uploadList->uptime);
                            len = cmd_up_mac_current_data(upCurrentData, &macRecordInfo);
                            cli_send_to_data(upCurrentData, len);
                            timer_queue_add(TIMEOUT_RESTART_SEND_DATA,
                                uploadList->timerId, 0, 0, 0, 0);
                        }
                    }


                }      
                timer_queue_add(TIMEOUT_DATA_INTVL(atoi(dev_conf.data.itvl)) + CLI_APP_1S, TIMRT_ID_MAC_DATA, 0, 0, 0, 0);
            }

            break;

        case TIMER_ID_MAC_OLD_DATA:
            if (cli_get_data_status() == DATA_SERVER_STATUS_CONNECTED) 
            {                
                //if command is running, pending 1s
                if ((cmd_queue != NULL) || (cmdList.commandNum != 0)) 
                {
                    timer_queue_add(CLI_APP_1S, event_queue[event_queue_e].socket, 0, 0, 0, 0);
                    break;
                }
                if ( atoi(dev_conf.data.enable) == 1 && macRecordInfo.maxId > 0 && macRecordInfo.maxId <= macRecordInfo.lastId  )
                {
                    macRecordInfo.realNum = 0;
                    uploadList = oldDataGetNotUseList(DATA_TYPE_MAC);
                    if ( uploadList == NULL )
                    { 
                        cli_app_log(CLI_LOG_WARNING, "all old list are using \n");
                    }
                    else
                    {     
                        macRecordInfo.oldId = macRecordInfo.minId;                       
                        getDbMacRecord(true, &macRecordInfo, &uploadList->startId, &uploadList->endId, false);

                    }
                    if ( macRecordInfo.realNum > 0 )
                    {
                        uploadList->isWaittingRsp = true;
                        uploadList->isOldData = true;
                         
                        setListUptime(&macRecordInfo.macInfoBuf[0].uptime, &uploadList->uptime, DATA_TYPE_MAC);
             
                        len = cmd_up_mac_current_data(upCurrentData, &macRecordInfo);
                        cli_send_to_data(upCurrentData, len);
                        timer_queue_add(TIMEOUT_RESTART_SEND_DATA,
                                uploadList->timerId, 0, 0, 0, 0);
                    }
                    if ( macRecordInfo.maxId <= macRecordInfo.minId && noUsingList(DATA_TYPE_MAC))
                    {
                        macRecordInfo.maxId = macRecordInfo.minId =  macRecordInfo.lastId =  0;
                    }
                }
                timer_queue_add(TIMEOUT_DATA_INTVL(atoi(dev_conf.data.itvl)) + CLI_APP_1S * 2, TIMER_ID_MAC_OLD_DATA, 0, 0, 0, 0);
            }
            break;          

        case TIMER_ID_MAC_UPOADLIST1:
        case TIMER_ID_MAC_UPOADLIST2:
        case TIMER_ID_MAC_UPOADLIST3:
        case TIMER_ID_MAC_UPOADLIST4:
        case TIMER_ID_MAC_UPOADLIST5:
            if (cli_get_data_status() == DATA_SERVER_STATUS_CONNECTED) 
            {
                uploadList = searchListByTimeId(event_queue[event_queue_e].socket, DATA_TYPE_MAC);

                if ( uploadList != NULL )
                {
                    macRecordInfo.realNum = 0;
                    cli_app_log(CLI_LOG_NOTICE, "resend data timerId is 0x%x, startId is %d endId is %d  time is %d\n", event_queue[event_queue_e].socket, 
                            uploadList->startId, uploadList->endId, uploadList->uptime);
                    getUploadMacFailedRecord(&macRecordInfo, uploadList->startId, uploadList->endId);
                    if ( macRecordInfo.realNum > 0 )
                    {
                        len = cmd_up_mac_current_data(upCurrentData, &macRecordInfo);
                        cli_send_to_data(upCurrentData, len);
                        timer_queue_add(TIMEOUT_RESTART_SEND_DATA,
                                event_queue[event_queue_e].socket, 0, 0, 0, 0); 
                    }
                    else
                    {
                        uploadList->isWaittingRsp = false;
                        uploadList->isOldData = false;
                    }
                }

            }
            break;
        

        case TIMER_ID_DATA_DEAD:
            if (strcmp(dev_conf.dev.protocol, ZHONGDUN) != 0)
                event_queue_add(IF_APP_EVENT_CLI_STOP, CLI_SOCK_ERR_DATA, 0, NULL);
            else
                event_queue_add(IF_APP_EVENT_INIT_CLI, CLI_INIT_DATA , 0, NULL);
            break;

        case TIMER_ID_MNG_DEAD:
            if (strcmp(dev_conf.dev.protocol, ZHONGDUN) != 0)
                event_queue_add(IF_APP_EVENT_CLI_STOP, CLI_SOCK_ERR_MNG, 0, NULL);
            else
                event_queue_add(IF_APP_EVENT_INIT_CLI, CLI_INIT_MNG , 0, NULL);
            break;

        case TIMER_ID_RESTART_CLI:
            cli_app_log(CLI_LOG_ERROR, "Restarting cli socket..... total times :%d.\n", *cli_rst_times);
            event_queue_add(IF_APP_EVENT_INIT_CLI, CLI_INIT_AUTH , 0, NULL);
            timer_queue_del(TIMER_ID_MNG_DEAD);
            timer_queue_del(TIMER_ID_DATA_DEAD);
            timer_queue_del(TIMER_ID_MNG_HEART_BEAT);
            timer_queue_del(TIMER_ID_DATA_HEART_BEAT);
            timer_queue_del(TIMER_ID_SYNC_FEEDBACK);
            timer_queue_del(TIMER_ID_CFG_FB);
            timer_queue_del(TIMER_ID_STATISTICS_FEEDBACK);
            if (atoi(dev_conf.dev.uploadMode) == 0)
            {
                timer_queue_del(TIMER_ID_SEND_OLD_DATA);
                timer_queue_del(TIMER_ID_UPOADLIST1);
                timer_queue_del(TIMER_ID_UPOADLIST2);
                timer_queue_del(TIMER_ID_UPOADLIST3);
                timer_queue_del(TIMER_ID_UPOADLIST4);
                timer_queue_del(TIMER_ID_UPOADLIST5);
                timer_queue_del(TIMER_ID_MAC_OLD_DATA);
                timer_queue_del(TIMRT_ID_MAC_DATA);
                timer_queue_del(TIMER_ID_MAC_UPOADLIST1);
                timer_queue_del(TIMER_ID_MAC_UPOADLIST2);
                timer_queue_del(TIMER_ID_MAC_UPOADLIST3);
                timer_queue_del(TIMER_ID_MAC_UPOADLIST4);
                timer_queue_del(TIMER_ID_MAC_UPOADLIST5);
            }
            break;

        case TIMER_ID_SYNC_FEEDBACK:
            if ((fd_times >= 1)) 
            {
                fd_times = 0;
                upload_data = false;
                cli_app_log(CLI_LOG_WARNING, "find can not recv reponse\n");
                //cli_app_log(CLI_LOG_INFO, "can not revice service response so we think socket disconnect\n");
                //cli_destroy_tcp_socket(CLI_TO_SRV_ALL_MASK);
                //timer_queue_add(TIMEOUT_RESTART_CLI,TIMER_ID_RESTART_CLI, 0, 0, 0, 0); 
                break; 
                //start timer to re-init client.                   
            }

            break;
        case TIMER_ID_RESTART_CREATE_PTHREAD:

            event_queue_add(IF_APP_EVENT_INIT_CLI, CLI_THREAD_CREATING, 0, NULL); 

            break;
        case TIMER_ID_RESTART_AUTH:

            event_queue_add(IF_APP_EVENT_INIT_CLI, CLI_INIT_AUTH, 0, NULL);

            break;
        case TIMER_ID_INTERNALE_HB:
            if ((cmd_queue != NULL) && cmd_queue_find_status(HT_CL_STATUS_DOING) != IF_APP_OK )
            {
                timer_queue_add(TIMEOUT_CMD_PENDING, TIMER_ID_PENDING_CMD,
                                event_queue[event_queue_e].module,
                                event_queue[event_queue_e].socket,
                                event_queue[event_queue_e].len,
                                event_queue[event_queue_e].data);
                                break;
            }
            if ((buf = buffer_allocate()) == NULL) 
            {
                cli_app_log(CLI_LOG_ERROR, "can not allocate buf \n");
                break;
            }
            if ( GetCliThreadStat() && GetMsgRcvThreadStat() )
            { 
                *(I32 *)buf_tmp = PARA_VALUE_SYSMONITOR_MODULE_OK;
                cli_app_log(CLI_LOG_INFO, "all thread is all right %d\n", *(I32 *)buf_tmp);
            }
            else
            {
                *(I32 *)buf_tmp = PARA_VALUE_SYSMONITOR_MODULE_ERROR;
            }
            
            device_handle_request(REQUEST_INTERNAL_HEARTBEAT, &dev_conf, buf, (I32 *)buf_tmp,  &buf_len);
            
            buffer_free(buf);
            timer_queue_add(TIMEOUT_INTERNAL_HEARTBEAT, TIMER_ID_INTERNALE_HB, 0, 0, 0, 0);
            break;     
            
        case TIMER_ID_STATISTICS_INTERVAL:
            //wait for api;
            cli_app_log(CLI_LOG_INFO, "------------------------- search cycle , chang serial num every time ------------------- \n");             
            if (cli_get_mng_status() == MNG_SERVER_STATUS_CONNECTED) 
            {
                I32 add_fb = 0;
                slot_num = 0;
                for (; slot_num < CELL_NUM; slot_num++)
                {                 
                    if (slotNum[slot_num] != 0)
                    {
                        len = count_every_bbu_upload_num(buf_tmp, slotNum[slot_num], slot_num + 1, serialnum);
                        cli_send_to_mng(buf_tmp, len);

                        add_fb = 1;
                        *(numRcv + slot_num) = 1;
                    }               
                }

                slot_num = 0;
                if (add_fb == 1)
                {
                    if (timer_queue_find(TIMER_ID_STATISTICS_FEEDBACK) < 0)
                    {
                        timer_queue_add(TIMEOUT_STATISTICS_FB(20), TIMER_ID_STATISTICS_FEEDBACK, 0, 0, 0, 0);
                    }
                } 
            }

            timer_queue_add(TIMEOUT_STATISTICS_INTVL(atoi(dev_conf.mng.cycle)), 
                    TIMER_ID_STATISTICS_INTERVAL, 0, 0, 0, 0);

            break;
        case TIMER_ID_STATISTICS_FEEDBACK :
            if (cli_get_mng_status() == MNG_SERVER_STATUS_CONNECTED)
            {
                for (; slot_num < CELL_NUM; slot_num++)
                {
                    if (*(numRcv + slot_num) != 0)
                    {
                       len = count_every_bbu_upload_num(buf_tmp, slotNum[slot_num], slot_num + 1, serialnum);
                       cli_send_to_mng(buf_tmp, len);                       
                    }
                }
                
                slot_num = 0;
                
                cli_app_log(CLI_LOG_INFO, "fb in timer id statistics \n");
            }
            
            timer_queue_add(TIMEOUT_STATISTICS_FB (20), TIMER_ID_STATISTICS_FEEDBACK, 0, 0, 0, 0);

            break;
        case TIMER_ID_SNIFFER_DOING:
            cmd_queue_set_status (*dcode, *id, HT_CL_STATUS_DOING, socket, type);
            if (cli_get_mng_status() == MNG_SERVER_STATUS_CONNECTED)
            {
                len = cmd_gen_mng_response(buf_tmp, BUFFER_BLOCK_SIZE, RST_DOING, NULL, *fcode, *type, cmdList);
                cli_send_to_mng(buf_tmp, len);
            }
            if (*dcode == CMD_LTE_DO_SNIFFER || *dcode == CMD_WCDMA_DO_SNIFFER)
                timer_queue_add(TIMEOUT_SNIFFER_FAILED, TIMER_ID_CMD_NO_RSP, 0, 0, 0, 0);
            else
                timer_queue_add(TIMEOUT_CMD_NO_RSP, TIMER_ID_CMD_NO_RSP, 0, 0, 0, 0);
            
            break;
        case TIMER_ID_CHNG_TAC_CYCLE:
            if ((cmd_queue != NULL) || (cmdList.commandNum != 0))
            {
                timer_queue_add(TIMEOUT_CMD_PENDING, TIMER_ID_PENDING_CMD,
                                event_queue[event_queue_e].module,
                                event_queue[event_queue_e].socket,
                                event_queue[event_queue_e].len,
                                event_queue[event_queue_e].data);
                break;
            }
            
            if ((buf = buffer_allocate()) == NULL) 
            {    
                break;
            }
            
            slot_num = event_queue[event_queue_e].len;
            for (; slot_num < LTE_CELL_NUM; slot_num++)
            {
                if (dev_status.bbuStatus[slot_num].bbuState  == 5)
                {
                    *(I32 *)buf_tmp = (slot_num +1);
                    updateSlot = slot_num ;
                    if (cmd_queue != NULL)
                    {
                        timer_queue_add(TIMEOUT_CMD_PENDING, TIMER_ID_PENDING_CMD,
                                        event_queue[event_queue_e].module,
                                        event_queue[event_queue_e].socket,
                                        (updateSlot),
                                        event_queue[event_queue_e].data);
                        break;
                    }
            
                    I32 tac = 0;     
                    tac = atoi(dev_conf.capLte.lte[slot_num].tac) + 1;                   
                    if (tac >= 65534) tac = 120;
                     
                    memset(dev_conf.capLte.lte[slot_num].tac, 0, DEV_INFO_NUM_LEN);
                    sprintf(dev_conf.capLte.lte[slot_num].tac, "%d", tac);
                    *id = device_handle_request(REQUEST_EUTRAN_UPDATA_CELL, &dev_conf, buf, (I32 *)buf_tmp, dcode);
                    cmd_queue_add(0, 0, TIMEOUT_CMD_QUEUE, *dcode, *id, 0);
                    timer_queue_add(TIMEOUT_CMD_NO_RSP, TIMER_ID_CMD_NO_RSP, 0, 0, 0, 0);
                }          
            }
            
            buffer_free(buf);
            
            if (slot_num == LTE_CELL_NUM)
            {
                timer_queue_add(TIMEOUT_CHNG_TAC_CYCLE(atoi(dev_conf.capLte.tac_cycle)), TIMER_ID_CHNG_TAC_CYCLE, 0, 0, 0, 0);
            }
            slot_num =0;            
            break;

        case TIMER_ID_CFG_FB:
            if (cli_get_mng_status() == MNG_SERVER_STATUS_CONNECTED)
            {               
                len = cmd_gen_local_config_response(0, buf_tmp, &dev_conf);
                cli_send_to_mng(buf_tmp, len);
                timer_queue_add(TIMEOUT_CFG_FB, TIMER_ID_CFG_FB, 0, 0, 0, 0);
            }              
            break;

       case TIMER_ID_REQUEST_BBU_STATE:          
           if ((cmd_queue != NULL) || (cmdList.commandNum != 0))
           {
                timer_queue_add(TIMEOUT_CMD_PENDING, TIMER_ID_PENDING_CMD,
                                event_queue[event_queue_e].module,
                                event_queue[event_queue_e].socket,
                                event_queue[event_queue_e].len,
                                event_queue[event_queue_e].data);
                break;
           }
           
           slot_num = 0;
           for (; slot_num < LTE_CELL_NUM; slot_num++)
           {
               if (dev_status.bbuStatus[slot_num].bbuState  == BBU_LOCATION)
                   break;

           }

           if (slot_num < LTE_CELL_NUM)
           { 
               *(I32 *)buf_tmp = (slot_num + 1);
               currentSlot = slot_num;
               if ((buf = buffer_allocate()) == NULL) 
               {
                   break;
               }                              

               *id = device_handle_request(REQUEST_EUTRAN_BBU_STATE, &dev_conf, buf, (I32 *)buf_tmp, dcode);
    
               if (*id >= 0)
               {
                   timer_queue_add(TIMEOUT_CMD_NO_RSP, TIMER_ID_CMD_NO_RSP, 0, 0, 0, 0);
                   cmd_queue_add(0, 0, TIMEOUT_CMD_QUEUE, *dcode, *id, 0);
               }

               buffer_free(buf); 
           }

           slot_num = 0;
           timer_queue_add(TIMEOUT_REQUEST_BBU_STATE, TIMER_ID_REQUEST_BBU_STATE, 0, 0, 0, 0);
           break;   
           
         
                               
       case TIMER_ID_BBU_CONFIG_CELL:                
           for (slot_num = 0; slot_num < LTE_CELL_NUM; slot_num ++)
           {
               if (dev_status.bbuStatus[slot_num].bbuState ==  BBU_UPGRADE
                       || dev_status.bbuStatus[slot_num].bbuState ==  BBU_UPGRADING )
               {
                   timer_queue_add(TIMEOUT_BBU_CONFIG_CELL, TIMER_ID_BBU_CONFIG_CELL, 0, 0, 0, 0);
                   slot_num = 0;
                   break;
               }
           } 

           if (slot_num == 0)
           {                                 
               break;              
           }  

           for (slot_num = 0; slot_num < LTE_CELL_NUM; slot_num ++)
           {
               cli_app_log(CLI_LOG_INFO, "bbu[%d] state [%d] \n", slot_num, dev_status.bbuStatus[slot_num].bbuState);
               if (dev_status.bbuStatus[slot_num].bbuState == BBU_REDAY)
               {
                   break;
               }
           }

           cli_app_log(CLI_LOG_INFO, "start timer to config cell slot is %d \n", slot_num);
           if (slot_num >= LTE_CELL_NUM)
           {
               slot_num = 0;
               break;
           }

           config_slot = (slot_num + 1);
           event_queue_add(IF_APP_EVENT_HANDLE_EUTRAN , REQUEST_EUTRAN_CONFIG_CELL, config_slot, NULL);
           cli_app_log(CLI_LOG_INFO, "restart timer to config cell\n");

           slot_num = 0;
           break;

       case TIMER_ID_REPORT_LOCAL_CONFIG:
           event_queue_add(IF_APP_EVENT_LOCAL_CONFIG, 0, 0, NULL);
           break;

        case TIMER_ID_REBOOT_BBU:
           if ((cmd_queue != NULL) || (cmdList.commandNum != 0))
           {
               timer_queue_add(TIMEOUT_CMD_PENDING,
                       TIMER_ID_PENDING_CMD,
                       event_queue[event_queue_e].module,
                       event_queue[event_queue_e].socket,
                       event_queue[event_queue_e].len,
                       event_queue[event_queue_e].data);
               break;

           }

           for (slot_num = 0; slot_num < LTE_CELL_NUM; slot_num++)
           {
               if ((dev_status.bbuStatus[slot_num].syncFialTm >= 5) 
                       &&(dev_status.bbuStatus[slot_num].syncState != INIT_SYNCED) 
                       && (dev_status.bbuStatus[slot_num].syncState != CNM_SYNCED) 
                       && (dev_status.bbuStatus[slot_num].syncState != GPS_SYNC) 
                       && (dev_status.bbuStatus[slot_num].syncState != GPS_INITALIZING) 
                       && (strcmp("TDD", dev_conf.capLte.lte[slot_num].desc) == 0))
               {
                   dev_status.bbuStatus[slot_num].syncFialTm = 0;
                   *(I32 *)buf_tmp = (slot_num + 1);
                   cli_app_log(CLI_LOG_WARNING, "sync failed reboot bbu is [%d] \n", (slot_num + 1));
                   if ((buf = buffer_allocate()) == NULL) 
                   {
                       cli_app_log(CLI_LOG_ERROR, "get buffer failed \n");
                       break;
                   }

                   *id = device_handle_request(REQUEST_EUTRAN_BBU_REBOOT, &dev_conf, buf, (I32 *)buf_tmp, dcode);                                  
                   if (*id >= 0) 
                   {
                       cmd_queue_add(0, 0, TIMEOUT_CMD_QUEUE, *dcode, *id, 0);
                       timer_queue_add(TIMEOUT_CMD_NO_RSP, TIMER_ID_CMD_NO_RSP, 0, 0, 0, 0);
                       cli_app_log(CLI_LOG_INFO, "----------------no rsp add -------------\n");
                   }

                   buffer_free(buf);
                   break;
               }
           }
           slot_num = 0;

           break;            
        case TIMER_ID_MANUAL_SNF:
           if (cmd_queue != NULL || cmdList.commandNum != 0)
           {
               timer_queue_add(TIMEOUT_CMD_PENDING,
                       TIMER_ID_PENDING_CMD,
                       event_queue[event_queue_e].module,
                       event_queue[event_queue_e].socket,
                       event_queue[event_queue_e].len,
                       event_queue[event_queue_e].data);
               break;
           }

           if (cmdList.commandNum == 0) break;

           if ((buf = buffer_allocate()) == NULL) 
           {
               cli_app_log(CLI_LOG_ERROR, "get buffer failed \n");
               break;
           }

           cli_app_log(CLI_LOG_INFO, "start to do manual sniffer\n");
           *id = device_handle_request(REQUEST_EUTRAN_MANUAL_SNIFFER, &dev_conf, buf, (I32 *)buf_tmp, dcode);                                  
           if (*id >= 0) 
           {
               cmd_queue_add(*fcode, 1, TIMEOUT_CMD_QUEUE, *dcode, *id, CT_SNIFFER);
               timer_queue_add(TIMEOUT_CMD_NO_RSP, TIMER_ID_CMD_NO_RSP, 0, 0, 0, 0);
           }

           buffer_free(buf);
           break;

       case TIMER_ID_RESTART_UPGRADE_BBU:
           if (cmd_queue != NULL)
           {
               timer_queue_add(TIMEOUT_CMD_PENDING, TIMER_ID_PENDING_CMD,
                               event_queue[event_queue_e].module,
                               event_queue[event_queue_e].socket,
                               event_queue[event_queue_e].len,
                               event_queue[event_queue_e].data);
                break;

           }

           for (slot_num = 0; slot_num < LTE_CELL_NUM; slot_num++)
           {
               if (dev_status.bbuStatus[slot_num].bbuState == BBU_UPGRADING)
               {
                   *(I32 *)buf_tmp = (slot_num + 1);                                              
                   slot_num = 0;
                   break;
               }
           }

           if ((buf = buffer_allocate()) == NULL) 
           {
               cli_app_log(CLI_LOG_ERROR, "get buffer failed \n");
               break;
           }

           *id = device_handle_request(REQUEST_EUTRAN_BBU_UPGRADE, &dev_conf, buf, (I32 *)buf_tmp, dcode);
           if (*id >= 0) 
            {
               cmd_queue_add(*fcode, *socket, TIMEOUT_CMD_QUEUE, *dcode, *id, *type);
               cmd_queue_set_status (*dcode, *id, HT_CL_STATUS_DOING, socket, type);   
           }

           buffer_free(buf);
           break;                           

       case TIMER_ID_BBU_POWER_CONFIG:
           for (slot_num = 0; slot_num < 7; slot_num++)
           {
               if ((dev_status.bbuStatus[slot_num].bbuState != BBU_NOT_EXIST)  )
               {
                   if (!powerEnable[slot_num])
                   {
                       powerEnable[slot_num] = true;
                       break;
                   }
               }
           }
           
           cli_app_log(CLI_LOG_INFO, "start timer to open power slot is %d \n", slot_num);
           if (slot_num >= LTE_CELL_NUM)
           {
               slot_num = 0;
               break;
           }
           
           config_slot = (slot_num + 1);
           if ( BlackListEnable)
               event_queue_add(IF_APP_EVENT_HANDLE_EUTRAN , REQUEST_EUTRAN_TX_POWER_CONFIG, config_slot, NULL);
           else
               event_queue_add(IF_APP_EVENT_HANDLE_EUTRAN , REQUEST_SHUTDOWN_ALLPOWER, config_slot, NULL);
           cli_app_log(CLI_LOG_INFO, "restart timer to config bbu[%d] power\n", config_slot);
           
           slot_num = 0;
           break;
       case TIMER_ID_WORKPERIOD:
           timer_queue_add(atoi(dev_conf.workMode.workPeriod) * 1000, TIMER_ID_WORKPERIOD, 0, 0, 0, 0);
           timer_queue_add(atoi(dev_conf.workMode.powerOffTime) * 1000, TIMER_ID_POWEROFFTM, 0, 0, 0, 0);
           event_queue_add(IF_APP_EVENT_HANDLE_EUTRAN , REQUEST_BBU_RADIO_OFF, 0, NULL);
           break;
           
       case TIMER_ID_POWEROFFTM:
           event_queue_add(IF_APP_EVENT_HANDLE_EUTRAN , REQUEST_BBU_RADIO_ON, 0, NULL);
           break;
                      
       case TIMER_ID_CMD_NO_RSP:
           cli_app_log(CLI_LOG_INFO, "can not get reponse form device in two min so del it to make sure the programe can work \n");
           if ((*dcode == CMD_CODE_EUTRAN_BBU_UPGRADE))
              break;
           if (*dcode == CMD_LTE_DO_SNIFFER)
           {
               timer_queue_add(TIMEOUT_LTE_POWER_ON, TIMER_ID_LTE_POWER_ON, 0, 0, 0, 0);
               cli_app_log(CLI_LOG_WARNING, "lte sniffer false so open all power \n");
           }
            if ((cmdList.commandNum > 0))
            {
                cmdList.commandNum = 0;
            }
           
            cmd_queue_del(*dcode, *id, socket, type);
            if (*type != 0)
            {
                xml_config_overwirte(CONFIG_MODE_RESTORE);
                xml_get_devConf(&dev_conf);
            }
           break;   
           
        case TIMER_ID_FTP_GET_DATA:
            if (getUploadState() && cmd_queue == NULL && atoi(dev_conf.ftp.ftpenable) == 1)
            {   
                time(&up_time[1]);
                up_time[1] -= 10;

                //we always start get data from last data.
                //here might be some performance issue, but
                //there is 500 phone data limitation which 
                //can avoid this issue.
                I32 time_tmp = up_time[1] - up_time[2];
#if 1
                if(time_tmp > max_time_missed) 
                {
                    max_time_missed = time_tmp;
                }

#endif
                *id = device_handle_request(REQUEST_UPDATE_GET_DATA, &dev_conf, buf_tmp, (I32 *) up_time, dcode);
                cmd_queue_add(0, 0, TIMEOUT_CMD_QUEUE, *dcode, *id, 0);

                cli_app_log(CLI_LOG_INFO,
                        "dcode is %08x, id is %08x, starttime is %lu, endtime is %lu max_time_missed is %d\n",
                        *dcode, *id, up_time[0], up_time[1] ,max_time_missed);
                timer_queue_add(CLI_APP_1S * atoi(dev_conf.ftp.ftptimer),   TIMER_ID_FTP_GET_DATA,  0, 0, 0, 0);

            }
            else
            {
                timer_queue_add(CLI_APP_1S, TIMER_ID_FTP_GET_DATA,  0, 0, 0, 0);
            }
 

            break;

        case TIMER_ID_FTP_UPLOAD_STATE:
            if (!getUploadState())
            {
                I32 uploadRet = PID_ERROR;
                uploadRet = checkUpload();
                if (uploadRet == PID_SUCCESS)
                {
                    *cli_rst_times = 0;
                    cli_app_log(CLI_LOG_INFO, "upload file success \n");
                    up_time[0] = up_time[1] = up_time[2]; 
                    memset(dev_conf.ftp.ftpuptime, 0, DEV_INFO_NUM_LEN);
                    sprintf(dev_conf.ftp.ftpuptime, "%lu", up_time[0]);
                    xml_handle_conf((I8 *)&dev_conf.ftp, IF_APP_SAVE_TIME);

                }
                else if (uploadRet == PID_GOING)
                {
                    timer_queue_add(CLI_APP_1S,  TIMER_ID_FTP_UPLOAD_STATE, 0, 0, 0, 0);
                }
                else if (uploadRet == PID_ERROR)
                {
                    if (uploadFile())
                        timer_queue_add(CLI_APP_1S,  TIMER_ID_FTP_UPLOAD_STATE, 0, 0, 0, 0);
                }
            }
            break;

        case TIMER_ID_FTP_TERMINAL_GET_DATA:
            if (getUploadState() && cmd_queue == NULL)
            {
                cli_app_log(CLI_LOG_INFO, "satrt to send terminal state \n");
                if (createTerminalDevInfo())
                {
                    if (uploadFile())
                        timer_queue_add(CLI_APP_1S,  TIMER_ID_FTP_UPLOAD_STATE, 0, 0, 0, 0);
                }
                else
                {
                    cli_app_log(CLI_LOG_WARNING, "create terminal state error \n");
                }
                timer_queue_add((CLI_APP_1S * 3610),   TIMER_ID_FTP_TERMINAL_GET_DATA,  0, 0, 0, 0);
            }
            else
            {
                timer_queue_add(CLI_APP_1S,   TIMER_ID_FTP_TERMINAL_GET_DATA,  0, 0, 0, 0);
            }
            break;
        
        case TIMER_ID_FTP_MAC_GET_DATA:
            if (getUploadState() && cmd_queue == NULL)
            {
                cli_app_log(CLI_LOG_INFO, "satrt to get mac infomation \n");
                if (saveMacToFtpFileOrSendByUdp(getMacFileName(), getcurrentFileRows(), &macRecordInfo.minId, &macRecordInfo.maxId))
                {
                    if (uploadFile())
                        timer_queue_add(CLI_APP_1S,  TIMER_ID_FTP_UPLOAD_STATE, 0, 0, 0, 0);
                }
                else
                {       
                    cli_app_log(CLI_LOG_NOTICE, "have not new mac infomation and reset file\n");
                    resetFileName();
                }
                timer_queue_add(CLI_APP_1S * atoi(dev_conf.ftp.ftpMactimer),   TIMER_ID_FTP_MAC_GET_DATA,  0, 0, 0, 0);
            }
            else
            {
                timer_queue_add(CLI_APP_1S,   TIMER_ID_FTP_MAC_GET_DATA,  0, 0, 0, 0);
            }
            break;

        case TIMER_ID_FTP_PLACE_GET_DATA:
            if (getUploadState() && cmd_queue == NULL)
            {
                cli_app_log(CLI_LOG_INFO, "satrt to send place state \n");
                if (strcmp(dev_conf.dev.protocol, FENGHUO) == 0)
                {
                    if (createPlaceStateInfo())
                    {
                        if (uploadFile())
                            timer_queue_add(CLI_APP_1S,  TIMER_ID_FTP_UPLOAD_STATE, 0, 0, 0, 0);
                    }
                    else
                    {
                        cli_app_log(CLI_LOG_WARNING, "create place state error \n");
                    }
                    timer_queue_add((CLI_APP_1S * 3600),   TIMER_ID_FTP_PLACE_GET_DATA,  0, 0, 0, 0);
                }
                else if (strcmp(dev_conf.dev.protocol, RENZIXING) == 0)
                {
                    if (createFtpFile(PLACE_STATE_TYPE))
                    {
                        if (uploadFile())
                            timer_queue_add(CLI_APP_1S,  TIMER_ID_FTP_UPLOAD_STATE, 0, 0, 0, 0);
                    }
                    else
                    {
                        cli_app_log(CLI_LOG_WARNING, "create place state error \n");
                    }
                    timer_queue_add((CLI_APP_1S * 3600 * 10),   TIMER_ID_FTP_PLACE_GET_DATA,  0, 0, 0, 0);
                }
            }
            else
            {
                timer_queue_add(CLI_APP_1S,   TIMER_ID_FTP_PLACE_GET_DATA,  0, 0, 0, 0);
            }
            break;

        case TIMER_ID_FTP_COMPANY_GET_DATA:
            if (getUploadState() && cmd_queue == NULL)
            {
                cli_app_log(CLI_LOG_INFO, "satrt to send place state \n");
                if (createCompanyBaseInfo())
                {
                    if (uploadFile())
                        timer_queue_add(CLI_APP_1S,  TIMER_ID_FTP_UPLOAD_STATE, 0, 0, 0, 0);
                }
                else
                {
                    cli_app_log(CLI_LOG_WARNING, "create place state error \n");
                }
                timer_queue_add((CLI_APP_1S * 3605),   TIMER_ID_FTP_COMPANY_GET_DATA,  0, 0, 0, 0);
            }
            else
            {
                timer_queue_add(CLI_APP_1S,   TIMER_ID_FTP_COMPANY_GET_DATA,  0, 0, 0, 0);
            }
            break;

        case TIMER_ID_FTP_DEVSTATE_GET_DATA:
            if (getUploadState() && cmd_queue == NULL)
            {
                cli_app_log(CLI_LOG_INFO, "satrt to send DEVICE state \n");
                if (strcmp(dev_conf.dev.protocol, FENGHUO) == 0)
                {
                    cmd_gen_ftp_devstatus(getDeviceMac12(), buf_tmp);
                    if (createDeviceJsonFile(buf_tmp))
                    {
                        if (uploadFile())
                            timer_queue_add(CLI_APP_1S,  TIMER_ID_FTP_UPLOAD_STATE, 0, 0, 0, 0);
                    }
                    else
                    {
                        cli_app_log(CLI_LOG_WARNING, "create place state error \n");
                    }
                    timer_queue_add((CLI_APP_1S * 300),   TIMER_ID_FTP_DEVSTATE_GET_DATA,  0, 0, 0, 0);
                }
                else if (strcmp(dev_conf.dev.protocol, RENZIXING) == 0)
                {
                    if (createFtpFile(DEV_STATE_TYPE))
                    {
                        if (uploadFile())
                            timer_queue_add(CLI_APP_1S,  TIMER_ID_FTP_UPLOAD_STATE, 0, 0, 0, 0);
                    }
                    else
                    {
                        cli_app_log(CLI_LOG_WARNING, "create place state error \n");
                    }
                    timer_queue_add((CLI_APP_1S * 3600 * 5),   TIMER_ID_FTP_DEVSTATE_GET_DATA,  0, 0, 0, 0);

                }
            }
            else
            {
                timer_queue_add(CLI_APP_1S,   TIMER_ID_FTP_DEVSTATE_GET_DATA,  0, 0, 0, 0);
            }
            break;
            

        case TIMER_ID_FTP_SITESTATE_UPLOAD:
             if (getUploadState() && cmd_queue == NULL)
            {
                cli_app_log(CLI_LOG_INFO, "satrt to send DEVICE state \n");
                cmd_gen_ftp_sitestatus(buf_tmp);
                if (createPlaceJsonFile(buf_tmp))
                {
                    if (uploadFile())
                        timer_queue_add(CLI_APP_1S,  TIMER_ID_FTP_UPLOAD_STATE, 0, 0, 0, 0);
                }
                else
                {
                    cli_app_log(CLI_LOG_WARNING, "create place state error \n");
                }
                timer_queue_add((CLI_APP_1S * 24 *3600),   TIMER_ID_FTP_SITESTATE_UPLOAD,  0, 0, 0, 0);
            }
            else
            {
                timer_queue_add(CLI_APP_1S,   TIMER_ID_FTP_SITESTATE_UPLOAD,  0, 0, 0, 0);
            }
            break;
           
            

        case TIMER_ID_UDP_HEARTBEAT:
            {
                if (strcmp(dev_conf.dev.protocol, HUANSHUO) == 0)
                {
                    timer_queue_add(CLI_APP_1S * 120, TIMER_ID_UDP_HEARTBEAT, 0, 0, 0, 0);
                    time_t rawtime;
                    time(&rawtime);
                    cli_app_log(CLI_LOG_INFO, "time to send udp hearteabt\n");
                    len = sprintf(buf_tmp, "%s\t%s\t%lu\t%s\t%s\t\r\n", dev_conf.ftp.ftpbsic, dev_mac, rawtime, dev_conf.dev.pos_lo, dev_conf.dev.pos_la);
                    sendHeartBeat(atoi(dev_conf.auth.port), buf_tmp, len);
                }
                else if (strcmp(dev_conf.dev.protocol, BAIZHUO) == 0)
                {
                    timer_queue_add(CLI_APP_1S * 10, TIMER_ID_UDP_HEARTBEAT, 0, 0, 0, 0);
                    sendBaiZhuoHb();
                }
            }
            break;

        case TIMER_ID_UDP_SN_DATA:
            {
                if (strcmp(dev_conf.dev.protocol, BAIZHUO) == 0)
                {
                    timer_queue_add(CLI_APP_1S * 120, TIMER_ID_UDP_SN_DATA, 0, 0, 0, 0);
                    sendImsiByUdp(&recordInfo.minId, &recordInfo.maxId);
                }

            }
            break;

        case TIMER_ID_UDP_MAC_DATA:
            {
                if (strcmp(dev_conf.dev.protocol, BAIZHUO) == 0)
                {
                    timer_queue_add(CLI_APP_1S * 120, TIMER_ID_UDP_MAC_DATA, 0, 0, 0, 0);
                    saveMacToFtpFileOrSendByUdp(NULL,  NULL, &macRecordInfo.minId, &macRecordInfo.maxId);
                }
            }
            break;

        case TIMER_ID_FTP_DEVICE_LOG:
            if (timer_queue_find(TIMER_ID_FTP_UPLOAD_STATE) < 0)
            {
                I32 uploadRet = PID_ERROR;
                uploadRet = checkUpLog();
                if (uploadRet == PID_ERROR)
                {
                    ftpLog.times++;
                    if ( ftpLog.times > 3 || !uploadLogFile())
                    {
                        I32 fcode = 0;
                        fcode = cmd_queue_del(*dcode, *id, socket, type);
                        if (socket) 	
					    {
                            len = cmd_gen_mng_response(buf_tmp, BUFFER_BLOCK_SIZE, RST_FAILED, NULL, fcode, *type, cmdList);
                            cli_send_to_mng(buf_tmp, len);
                        }
                    }
                    else
                    {
                        timer_queue_add(CLI_APP_1S * 5,  TIMER_ID_FTP_DEVICE_LOG, 0, 0, 0, 0);
                    }
                }
                else if (uploadRet == PID_GOING)
                {
                    timer_queue_add(CLI_APP_1S * 5,  TIMER_ID_FTP_DEVICE_LOG, 0, 0, 0, 0);
                }
                else
                {
                    I32 fcode = 0;
                    fcode = cmd_queue_del(*dcode, *id, socket, type);
                    if (socket) 	
					{
                        len = cmd_gen_mng_response(buf_tmp, BUFFER_BLOCK_SIZE, RST_SUCESS, NULL, fcode, *type, cmdList);
                        cli_send_to_mng(buf_tmp, len);
                    }

                }

            }
            else
                timer_queue_add(CLI_APP_1S * 5,  TIMER_ID_FTP_DEVICE_LOG, 0, 0, 0, 0);
            break;

        case TIMER_ID_LTE_POWER_ON:
            if (cmd_queue != NULL || cmdList.commandNum != 0)
            {
                timer_queue_add(TIMEOUT_CMD_PENDING,
                        TIMER_ID_PENDING_CMD,
                        event_queue[event_queue_e].module,
                        event_queue[event_queue_e].socket,
                        event_queue[event_queue_e].len,
                        event_queue[event_queue_e].data);
                break;
            }

            for (; powerSlot < LTE_CELL_NUM; powerSlot++)
            {
                if (atoi(dev_conf.capLte.lte[powerSlot].enable) == 1)
                    break;
            }
            if (powerSlot >= LTE_CELL_NUM)
            {
                powerSlot = 0;
                break;
            }
            if ((buf = buffer_allocate()) == NULL) 
            {
                cli_app_log(CLI_LOG_ERROR, "get buffer failed \n");
                break;
            }
            *(I32 *)buf_tmp = ++powerSlot;
            cli_app_log(CLI_LOG_INFO, "start to open all LTE power\n");
            *id = device_handle_request(REQUEST_LTE_OPEN_ALL_POWER, &dev_conf, buf, (I32 *)buf_tmp, dcode);                                  
            if (*id >= 0) 
            {
                cmd_queue_add(*fcode, 0, TIMEOUT_CMD_QUEUE, *dcode, *id, 0);
                timer_queue_add(TIMEOUT_CMD_NO_RSP, TIMER_ID_CMD_NO_RSP, 0, 0, 0, 0);
            }
            timer_queue_add(TIMEOUT_LTE_POWER_ON, TIMER_ID_LTE_POWER_ON, 0, 0, 0, 0);
            buffer_free(buf);
            break;

        case TIMER_ID_WCDMA_POWER_ON: 
            if (cmd_queue != NULL || cmdList.commandNum != 0)
            {
                timer_queue_add(TIMEOUT_CMD_PENDING,
                        TIMER_ID_PENDING_CMD,
                        event_queue[event_queue_e].module,
                        event_queue[event_queue_e].socket,
                        event_queue[event_queue_e].len,
                        event_queue[event_queue_e].data);
                break;
            }

            if ((buf = buffer_allocate()) == NULL) 
            {
                cli_app_log(CLI_LOG_ERROR, "get buffer failed \n");
                break;
            }

            cli_app_log(CLI_LOG_INFO, "start to open all WCDMA power\n");
            *id = device_handle_request(REQUEST_UPDATA_WCDMA_ENABLE, &dev_conf, buf, (I32 *)buf_tmp, dcode);                                  
            if (*id >= 0) 
            {
                cmd_queue_add(*fcode, 0, TIMEOUT_CMD_QUEUE, *dcode, *id, 0);
                timer_queue_add(TIMEOUT_CMD_NO_RSP, TIMER_ID_CMD_NO_RSP, 0, 0, 0, 0);
            }

            buffer_free(buf);
            break;

        case TIMER_ID_MOBILE_SN_RECORD:
        case TIMER_ID_UNICOM_SN_RECORD:
            {
                ZHONGDUNLIST list;
                U16 Sn = 0;
                bool isMobile = false;
                if (event_queue[event_queue_e].socket == TIMER_ID_MOBILE_SN_RECORD)
                {
                    isMobile = true;
                    if (cli_get_mng_status() != MNG_SERVER_STATUS_CONNECTED)
                        break;
                }
                else
                {
                    isMobile = false;
                    if (cli_get_data_status() == DATA_SERVER_STATUS_CONNECTED)
                        break;
                }
                if (getRecordBySn(isMobile, &list, &Sn))
                {
                    if (isMobile)
                    {
                        timer_queue_add(CLI_APP_1S * 2, TIMER_ID_MOBILE_SN_RECORD, 0, 0, 0, 0);
                    }
                    else
                    {
                        timer_queue_add(CLI_APP_1S * 2, TIMER_ID_UNICOM_SN_RECORD, 0, 0, 0, 0);
                    }
                }
                len = packRecordBySn(isMobile, &list, Sn, buf_tmp);
                cli_send_to_tcp(getSock(isMobile), buf_tmp, len, 0);
                

            }
            break;

        default:
            break;

    }

    buffer_free(buf_tmp);
    return;
}

void handle_event_from_device(I32 *deviceNumber, I32 *histData, I32 *sock, I32 *rstTime, I32 *numReceive, 
                              I32 *funcode, I32 *deCode, I32 *cmdType, I32 *identity, UPDATA_CACHE *data, I32 * times)
{
    I8 *buf = NULL;
    I8 *buf_tmp = NULL;
    I32 buf_len = 0, len = 0;
    I32 currentSlot = 0;    
    I32 conf_req = 0;    
    I32 bbuRp = 0;
    GPSINFO *gpsinfo;
    SYS_INFO *sysInfo;
    BBU_STATUS *bbuStatus;
    DEV_SET_RSP *rsp;
    SOFTWARE_VERSION_INFO *Info;
    GPSPOSITION *position;

    I32 slot_num = 0;
    I32 *manual_times = times; //it is a flag to count slot
    I32 *id = identity;
    I32 *type = cmdType;
    I32 *dcode = deCode;
    I32 *fcode = funcode;
    I32 *addDevNum = deviceNumber;
    I32 *historical_data = histData;
    I32 *socket = sock; 
    UPDATA_CACHE *updata = data;

    if ((buf = event_queue[event_queue_e].data) == NULL || 
        (buf_len = event_queue[event_queue_e].len) == 0) 
	{
		return;
    }

    cli_app_log(CLI_LOG_INFO, "rcv device msg, len is %d: \n", buf_len);
    buffer_dump_log(buf, buf_len, CLI_LOG_DEFAULT);    
        
    if ((buf_tmp = buffer_allocate()) == NULL) 
	{
        buffer_free(buf);
        return;
    }
    
    conf_req = device_handle_response(buf, (I32 *) buf_tmp);
    cli_app_log(CLI_LOG_INFO, "conf_req is %08x\n", conf_req);

    if (conf_req & RESPONSE_SET_RESPONSE) 
    {
        rsp = (DEV_SET_RSP *) buf_tmp;

        if (rsp->code == PARA_VALUE_RESULT_SUCCESS) 
        {
			cli_app_log(CLI_LOG_INFO, "set response OK\n");
            if (rsp->dcode == CMD_CODE_EUTRAN_START_SNIFFER)
            {
                (*manual_times)++;
            }

            if (*dcode != CMD_CODE_PHONE_INFO_TRANSFER_START && *dcode != CMD_CODE_BLACKLIST_IMSI_TRANSFER_START) 
            {
                if ((*fcode = cmd_queue_del(rsp->dcode, rsp->id, socket, type)) >= 0) 
                {
                    if ((rsp->dcode == CMD_CODE_EUTRAN_START_SNIFFER) || (rsp->dcode == CMD_CODE_EUTRAN_CONFIG_CELL))
                    {
                        if (timer_queue_find(TIMER_ID_SNIFFER_DOING) == 0)
                            timer_queue_del(TIMER_ID_SNIFFER_DOING);
                        else
                            timer_queue_del(TIMER_ID_CMD_NO_RSP);                                                              
                    }
                    else
                         timer_queue_del(TIMER_ID_CMD_NO_RSP);

                    if (rsp->dcode == CMD_CODE_SYS_UPGRADE)
                    {
                         timer_queue_del(TIMER_ID_UPGREAD_FAILED);
                    }
    
                    if (rsp->dcode == CMD_CODE_EUTRAN_BLACKLIST_SETTING)
                    {
                        BlackListEnable = true;
                        if (timer_queue_find(TIMER_ID_BBU_POWER_CONFIG) < 0) 
                            timer_queue_add(TIMEOUT_BBU_CONFIG_CELL, TIMER_ID_BBU_POWER_CONFIG, 0, 0, 0, 0);            
                    }   
                                 
                    if (cmdList.commandNum > 0)
                        cmdList.commandList[cmdList.cmdIndex].result = IF_APP_OK;

                    if ((rsp->dcode == CMD_CODE_SYS_UPGRADE))      
                    {
                         cli_app_log(CLI_LOG_NOTICE, "down load upgrade packet success\n");
                         if (rsp->errcode == PARA_VALUE_UPGRADE_TDD || rsp->errcode == PARA_VALUE_UPGRADE_X86ANDTDD)
                         {
                             cmdList.commandNum++;
                             for (slot_num = 0; slot_num < 7; slot_num++)
                             {
                                 if (atoi(dev_conf.capLte.lte[slot_num].enable) == 1
                                     && strcmp("TDD", dev_conf.capLte.lte[slot_num].desc) == 0)
                                 {
                                     cmdList.commandList[cmdList.commandNum - 1].cellId = (slot_num + 1);
                                     cmdList.commandList[cmdList.commandNum - 1].cmdId = REQUEST_EUTRAN_BBU_UPGRADE;
                                     cmdList.commandNum++;
                                     dev_status.bbuStatus[slot_num].bbuState = BBU_UPGRADE;
                                     rsp->dcode = CMD_CODE_EUTRAN_BBU_UPGRADE;
                                     cli_app_log(CLI_LOG_NOTICE, "upgrade bbu is %d \n", slot_num + 1);
                                 }
                             }
                             if ( rsp->errcode == PARA_VALUE_UPGRADE_X86ANDTDD)
                             {
                                 cmdList.commandList[cmdList.commandNum - 1].cellId = 0;
                                 cmdList.commandList[cmdList.commandNum - 1].cmdId = REQUEST_UPGRADE_X86;
                                 cmdList.commandNum++;                              

                             }
                         }
                         else if (rsp->errcode == PARA_VALUE_UPGRADE_FDD || rsp->errcode == PARA_VALUE_UPGRADE_X86ANDFDD)
                         {
                             cmdList.commandNum++;
                             for (slot_num = 0; slot_num < 7; slot_num++)
                             {
                                 if (atoi(dev_conf.capLte.lte[slot_num].enable) == 1
                                     && strcmp("FDD", dev_conf.capLte.lte[slot_num].desc) == 0)
                                 {

                                     cmdList.commandList[cmdList.commandNum - 1].cellId = (slot_num + 1);
                                     cmdList.commandList[cmdList.commandNum - 1].cmdId = REQUEST_EUTRAN_BBU_UPGRADE;
                                     cmdList.commandNum++;
                                     dev_status.bbuStatus[slot_num].bbuState = BBU_UPGRADE;
                                     rsp->dcode = CMD_CODE_EUTRAN_BBU_UPGRADE;
                                     cli_app_log(CLI_LOG_NOTICE, "upgrade bbu is %d \n", slot_num + 1);
                                 }
                             }
                             if ( rsp->errcode == PARA_VALUE_UPGRADE_X86ANDFDD)
                             {
                                 cmdList.commandList[cmdList.commandNum - 1].cellId = 0;
                                 cmdList.commandList[cmdList.commandNum - 1].cmdId = REQUEST_UPGRADE_X86;
                                 cmdList.commandNum++;                              

                             }
                         }
                         else if (rsp->errcode == PARA_VALUE_UPGRADE_ALL_BASEBAND || rsp->errcode == PARA_VALUE_UPGRADE_ALL )
                         {
                             cmdList.commandNum++;
                             for (slot_num = 0; slot_num < 7; slot_num++)
                             {
                                 if (atoi(dev_conf.capLte.lte[slot_num].enable) == 1)
                                 {
                                     cmdList.commandList[cmdList.commandNum - 1].cellId = (slot_num + 1);
                                     cmdList.commandList[cmdList.commandNum - 1].cmdId = REQUEST_EUTRAN_BBU_UPGRADE;
                                     cmdList.commandNum++;
                                     dev_status.bbuStatus[slot_num].bbuState = BBU_UPGRADE;
                                     rsp->dcode = CMD_CODE_EUTRAN_BBU_UPGRADE;
                                     cli_app_log(CLI_LOG_NOTICE, "upgrade bbu is %d \n", (slot_num + 1));
                                 }
                             }
                             if ( rsp->errcode == PARA_VALUE_UPGRADE_ALL )
                             {
                                 cmdList.commandList[cmdList.commandNum - 1].cellId = 0;
                                 cmdList.commandList[cmdList.commandNum - 1].cmdId = REQUEST_UPGRADE_X86;
                                 cmdList.commandNum++;                              

                             }
                         }
                         else if (rsp->errcode == PARA_VALUE_UPGRADE_GSM)
                         {
                            cmdList.commandNum++;
                            cmdList.commandList[cmdList.commandNum - 1].cellId = 0;
                            cmdList.commandList[cmdList.commandNum - 1].cmdId = REQUEST_GSM_UPGRADE;
                            cmdList.commandNum++;                               
                         }
                    }        

                    if (rsp->dcode == CMD_CODE_EUTRAN_BBU_UPGRADE)
                    {
                        for (slot_num = 0; slot_num < CELL_NUM; slot_num++)
                        {
                            if (dev_status.bbuStatus[slot_num].bbuState == BBU_UPGRADING)
                            {
                                dev_status.bbuStatus[slot_num].bbuState = BBU_UPGRADE_SUCCESS;
                                cli_app_log(CLI_LOG_NOTICE, "upgrade BBU[%d] success \n", (slot_num + 1));

                            }
                            if (dev_status.bbuStatus[slot_num].bbuState == BBU_UPGRADE)
                            {
                                *(I32 *)buf_tmp = (slot_num + 1);
                                cli_app_log(CLI_LOG_NOTICE, "start to upgrade BBU[%d] \n", *(I32 *)buf_tmp);
                                rsp->dcode = CMD_CODE_EUTRAN_BBU_UPGRADE;
                                dev_status.bbuStatus[slot_num].bbuState = BBU_UPGRADING;
                                slot_num = 0;
                                upgradeFailTm = 0;
                                break;
                            }
                         }
                         if ( slot_num == CELL_NUM && cmdList.commandNum == 2 )
                         {
                             rsp->dcode = CMD_CODE_FWM_UPGRADE_X86;
                             cli_app_log(CLI_LOG_NOTICE, "start to upgrade x86 \n");     
                         }
                    }  

                    if (rsp->dcode == CMD_LTE_DO_SNIFFER)
                    {   
                        timer_queue_add(TIMEOUT_LTE_POWER_ON, TIMER_ID_LTE_POWER_ON, 0, 0, 0, 0);
                    }
                    else if (rsp->dcode == CMD_WCDMA_DO_SNIFFER)
                    {
                        timer_queue_add(TIMEOUT_LTE_POWER_ON, TIMER_ID_WCDMA_POWER_ON, 0, 0, 0, 0);                
                    }
    
                    if ((cmdList.commandNum > 0) && (type != 0))
                    {
                        cmdList.commandNum--;
                        if (cmdList.commandNum > 0)
                        {
                            conf_req = cmdList.commandList[cmdList.cmdIndex++].cmdId;
                            if (conf_req != IF_APP_OK)
                            {    
                                if (conf_req != REQUEST_EUTRAN_MANUAL_SNIFFER)
                                {       
			                        *id = device_handle_request(conf_req, &dev_conf, buf, (I32 *)buf_tmp, dcode);
                                    if (*id >= 0) 
		      		                {
                    	                cmd_queue_add(*fcode, *socket, TIMEOUT_CMD_QUEUE, *dcode, *id, *type);
                                        if ((*dcode == CMD_CODE_EUTRAN_START_SNIFFER) || 
                                            (*dcode == CMD_CODE_EUTRAN_CONFIG_CELL) || 
                                            (*dcode == CMD_LTE_DO_SNIFFER) || 
                                             (*dcode == CMD_WCDMA_DO_SNIFFER))
                                        {
                                            timer_queue_add(TIMEOUT_SNIFFER_DOING,
                                        		            TIMER_ID_SNIFFER_DOING,0, 0, 0, 0);
                                        }		
                                        else
                                        {    
                                           timer_queue_add(TIMEOUT_CMD_NO_RSP, TIMER_ID_CMD_NO_RSP, 0, 0, 0, 0);
                                        }   
                                          
                                     }
                                     if (*dcode == CMD_CODE_EUTRAN_BBU_UPGRADE || *dcode == CMD_LTE_DO_SNIFFER)
                                     {   
                                         cmd_queue_set_status (*dcode, *id, HT_CL_STATUS_DOING, socket, type); 
                                     }    
                                 }
                                 else
                                 {   
                                     timer_queue_add(TIMEOUT_MANUAL_SNF, TIMER_ID_MANUAL_SNF, 0, 0, 0, 0); 
                                 }      
                            }
                         }      
                    }


 
                    if ((cmdList.commandNum == 0) && (*type != 0))
                    {
                        if (*socket) 	
					    {
                            len = cmd_gen_mng_response(buf, BUFFER_BLOCK_SIZE, RST_SUCESS, NULL, *fcode, *type, cmdList);
                            if (cli_sock_is_mng(*socket) == IF_APP_OK)
                                cli_send_to_mng(buf, len);
                            else
                                cli_send_to_data(buf, len);

                        }
                        cleanCmdList();
                        if (rsp->dcode == CMD_CODE_SYS_REBOOT )
                        {
                            cli_destroy_tcp_socket(CLI_TO_SRV_ALL_MASK);
                        }
                    }
                    if (*fcode == CT_TIME_SYNC) 
					{
						//because single command mode, we are free now.
                        time(&up_time[1]);
						//if current time is earlier than last valid data time, update it, last 1s data in back.
						if(up_time[1] < up_time[2]) 
                        {
                        	up_time[2] = up_time[0] = up_time[1];
							memset(up_back, 0, 0x100);
							timer_queue_del(TIMER_ID_SYNC_FEEDBACK);
                        }
                    }
                } 
				else 
				{
                    cli_app_log(CLI_LOG_ERROR, "CMD_QUEUE ERROR: can not find command\n");
                }
            }
        } 
        else if (rsp->code == PARA_VALUE_RESULT_FAILED) 
		{
            cli_app_log(CLI_LOG_WARNING, "set response fail, code %08x\n", rsp->errcode);
            //if rsp code == CMD_CODE_PHONE_INFO_TRANSFER_START means  historical_time is wrong
            if (*dcode == CMD_CODE_PHONE_INFO_TRANSFER_START) 
            {
                *historical_data = 0;
            }   
            if (cmdList.commandNum > 0)
                 cmdList.commandList[cmdList.cmdIndex++].result = IF_APP_OK;
            if (cmd_queue_del(rsp->dcode, rsp->id, socket, type) >= 0) 
		    {		            
                if ((rsp->dcode == CMD_CODE_EUTRAN_START_SNIFFER) || 
                    (rsp->dcode == CMD_CODE_EUTRAN_CONFIG_CELL) || 
                    (rsp->dcode == CMD_LTE_DO_SNIFFER) ||
                    (rsp->dcode == CMD_WCDMA_DO_SNIFFER))
                {                    
                    if (timer_queue_find(TIMER_ID_SNIFFER_DOING) == 0)
                    {
                        timer_queue_del(TIMER_ID_SNIFFER_DOING);
                    }
                    else
                        timer_queue_del(TIMER_ID_CMD_NO_RSP); 
                }
                else
                     timer_queue_del(TIMER_ID_CMD_NO_RSP);
            
                if (rsp->dcode == CMD_CODE_SYS_UPGRADE)
                {
                     timer_queue_del(TIMER_ID_UPGREAD_FAILED);
                }
            
                if ((rsp->dcode == CMD_CODE_EUTRAN_BBU_UPGRADE) && (upgradeFailTm < 3))
                {
                     upgradeFailTm++;
                     if (timer_queue_find(TIMER_ID_RESTART_UPGRADE_BBU) < 0)
                          timer_queue_add(TIMEOUT_RESTART_UPGRADE_BBU, TIMER_ID_RESTART_UPGRADE_BBU, 0, 0, 0, 0);
                }
                else                              
                {
                    if (rsp->dcode == CMD_CODE_EUTRAN_BBU_UPGRADE)
                    {
                        for (slot_num = 0; slot_num < CELL_NUM; slot_num++)
                        { 
                            if ( dev_status.bbuStatus[slot_num].bbuState >= BBU_UPGRADE)
                            {
                                dev_status.bbuStatus[slot_num].bbuState = BBU_UPGRADE_FAILED;
                                cli_app_log(CLI_LOG_WARNING, "upgrade BBU[%d] failed \n", (slot_num + 1));
                            }
                        }
                        
                        upgradeFailTm = 0;
                    }
                    
                    if (rsp->dcode == CMD_LTE_DO_SNIFFER)
                    {   
                        timer_queue_add(TIMEOUT_LTE_POWER_ON, TIMER_ID_LTE_POWER_ON, 0, 0, 0, 0);
                    }
                    else if (rsp->dcode == CMD_WCDMA_DO_SNIFFER)
                    {
                        timer_queue_add(TIMEOUT_LTE_POWER_ON, TIMER_ID_WCDMA_POWER_ON, 0, 0, 0, 0);                
                    }
                    if (*type != 0)
                    {
                        cleanCmdList();
		            }
                    if ( *socket) 
		        	{
                        if ((*type!=0) )
                        {
                   
                            len = cmd_gen_mng_response(buf, BUFFER_BLOCK_SIZE, RST_FAILED,
                                               device_get_error_string (rsp->errcode), *fcode, *type, cmdList);
                            if (cli_sock_is_mng(*socket) == IF_APP_OK)
                                cli_send_to_mng(buf, len);
                            else 
                                cli_send_to_data(buf, len);
                        }
                   
                        xml_config_overwirte(CONFIG_MODE_RESTORE);
                        xml_get_devConf(&dev_conf);
                    } 
                } 
            } 
		    else 
		    {
                cli_app_log(CLI_LOG_ERROR, "CMD_QUEUE ERROR: can not find command\n");
            }
        } 
		else if (rsp->code == PARA_VALUE_RESULT_DOING) 
		{
            cli_app_log(CLI_LOG_INFO, "set response doing.\n");

            //doing means another command is doing ,we must wait last command end
            if ((rsp->dcode == CMD_CODE_EUTRAN_START_SNIFFER )|| ((rsp->dcode == CMD_CODE_EUTRAN_CONFIG_CELL)))
            {
                if ( dev_status.bbuStatus[slot_num].bbuState == BBU_SNFING)
                     dev_status.bbuStatus[slot_num].bbuState= BBU_REDAY;
                timer_queue_del(TIMER_ID_SNIFFER_DOING);
            }
            else
                 timer_queue_del(TIMER_ID_CMD_NO_RSP);

            if (rsp->dcode==CMD_CODE_SYS_UPGRADE || rsp->dcode == CMD_CODE_SYS_COLLECT_LOG)
            {
                cmd_queue_set_status (rsp->dcode, rsp->id, HT_CL_STATUS_DOING, socket, type);
                if (rsp->dcode==CMD_CODE_SYS_UPGRADE)
                    timer_queue_add(TIMEOUT_UPGRADE_FIALED, TIMER_ID_UPGREAD_FAILED, 0, 0, 0, 0);
                else if (rsp->dcode==CMD_CODE_SYS_COLLECT_LOG)
                {
                    if (uploadLogFile())
                        timer_queue_add(CLI_APP_1S * 5, TIMER_ID_FTP_DEVICE_LOG, 0, 0, 0, 0);
                    else
                    {
                        cmd_queue_del(rsp->dcode, rsp->id, socket, type);
                        rsp->dcode |= 0x0C00;
                    }
                }
            }
			else
                cmd_queue_del(rsp->dcode, rsp->id, socket, type);

            if (*socket) 
            {
                if ((rsp->dcode | 0x0C00) != 0x0C00)
                    len = cmd_gen_mng_response(buf, BUFFER_BLOCK_SIZE, RST_DOING, NULL, *fcode, *type, cmdList);
				else
                {
					len = cmd_gen_mng_response(buf, BUFFER_BLOCK_SIZE, RST_FAILED, NULL, *fcode, *type, cmdList);
                    xml_config_overwirte(CONFIG_MODE_RESTORE);
                    xml_get_devConf(&dev_conf);

                }
                if (cli_sock_is_mng(*socket) == IF_APP_OK)
                    cli_send_to_mng(buf, len);
                else 
                    cli_send_to_data(buf, len);
            
            }

            if ((*type != 0))
            {
                cleanCmdList();
            }

        }
    } 
	else if (conf_req & RESPONSE_GET_RESPONSE) 
	{
		conf_req &= RESPONSE_TYPE_MASK;
        switch (conf_req) 
		{
            case IF_APP_REP_STATUS:
              				
                if ( (cli_get_mng_status() == MNG_SERVER_STATUS_CONNECTED || (strcmp(dev_conf.dev.protocol, NANFEI) == 0)) && atoi(dev_conf.mng.enable)) 
				{
					dev_status.dev_temp = 50;
                    if (dev_status.cpu_load < 5) 
					{
                        dev_status.cpu_load = 5;
                    }

                    len = cmd_gen_devstatus_string(atoi(dev_conf.dev.devtype), &dev_status, buf, &dev_conf);
                    cli_send_to_mng(buf, len);
                    cli_app_log(CLI_LOG_INFO, "send devstatus \n");
                }
                
                break;
			case IF_APP_REP_SYSINFO:
				rsp = (DEV_SET_RSP *) buf_tmp;
                sysInfo = (SYS_INFO *)(buf_tmp + sizeof(DEV_SET_RSP));
                timer_queue_del(TIMER_ID_CMD_NO_RSP);
				if(cmd_queue_del(rsp->dcode, rsp->id, socket, type) < 0) 
				{
                	cli_app_log(CLI_LOG_ERROR, "DEBUG get system info: CANNOT find command\n");
                } 
				else 
                {
                }

                memcpy(dev_mac, sysInfo->mac_addr, 32);
                if (cli_get_mng_status() == MNG_SERVER_STATUS_CONNECTED)
                {
                    len = cmd_gen_sys_info_string(sysInfo, buf);
                    if (cli_sock_is_mng(*socket) == IF_APP_OK)
                        cli_send_to_mng(buf, len);
                    else 
                        cli_send_to_data(buf, len);
                  
                }
                
                break;
			case IF_APP_SR_GPSINFO:
#ifdef	MODULE_GPS_BOARD
				rsp = (DEV_SET_RSP *)buf_tmp;
				gpsinfo = (GPSINFO *) (buf_tmp + sizeof(DEV_SET_RSP));
                timer_queue_del(TIMER_ID_CMD_NO_RSP);
				len = cmd_gen_gpsboardstatus_string(&gpsboardinfo, buf);
				cli_send_to_mng(buf, len);
#else
				rsp = (DEV_SET_RSP *)buf_tmp;
				gpsinfo = (GPSINFO *) (buf_tmp + sizeof(DEV_SET_RSP));
                timer_queue_del(TIMER_ID_CMD_NO_RSP);
         
				if(cmd_queue_del(rsp->dcode, rsp->id, socket, type) < 0) 
				{
                	cli_app_log(CLI_LOG_ERROR, "DEBUG get gps info: CANNOT find command\n");
                } 
				else 
				{
					cli_app_log(CLI_LOG_NOTICE, "DEBUG get gps info Done, long is %f      %f       %f\n", 
					            gpsinfo->longitude, gpsinfo->latitude, gpsinfo->altitude);
				}
				len = cmd_gen_gpsstatus_string(gpsinfo, buf);
				cli_send_to_mng(buf, len);
#endif
				break;	

            case IF_APP_SR_VERSION:
                rsp = (DEV_SET_RSP *) buf_tmp;
                timer_queue_del(TIMER_ID_CMD_NO_RSP);
         
				if(cmd_queue_del(rsp->dcode, rsp->id, socket, type) < 0) 
				{
                	cli_app_log(CLI_LOG_ERROR, "DEBUG get gps info: CANNOT find command\n");
                } 
                len = cmd_gen_bbu_version(buf, (buf_tmp + sizeof(DEV_SET_RSP)), 8);
            	cli_send_to_mng(buf, len);

                break;


            case IF_APP_SR_BBU_STATE:
                // timer_queue_del(TIMER_ID_CMD_NO_RSP);
 				rsp = (DEV_SET_RSP *) buf_tmp;
                timer_queue_del(TIMER_ID_CMD_NO_RSP);
                cli_app_log(CLI_LOG_DEFAULT, "----------------no rsp del -------------\n");
                if(cmd_queue_del(rsp->dcode, rsp->id, socket, type) < 0) 
                {
                    cli_app_log(CLI_LOG_ERROR, "DEBUG get BBU info: CANNOT find command\n");
                }      

				if (rsp->code == PARA_VALUE_RESULT_SUCCESS)
                { 
                    slot_num = rsp->errcode;
                    slot_num--;
                    bbuStatus =(BBU_STATUS *)(buf_tmp + sizeof(DEV_SET_RSP));
                    dev_status.bbuStatus[slot_num].memusage = bbuStatus->memusage;
                    dev_status.bbuStatus[slot_num].cpuusage = bbuStatus->cpuusage;
                    dev_status.bbuStatus[slot_num].cputemp = bbuStatus->cputemp;
                    dev_status.bbuStatus[slot_num].boardtemp = bbuStatus->boardtemp;
              
                    slot_num ++;
                }
                else if (*(I32 *) buf_tmp == PARA_VALUE_RESULT_DOING)
                { 
                    break;                                       
                }
                else
                    slot_num = (currentSlot + 1);

                for (; slot_num < LTE_CELL_NUM; slot_num++)
                {
                    if (dev_status.bbuStatus[slot_num].bbuState == BBU_LOCATION)
                    break;
                }
    
                if (slot_num < LTE_CELL_NUM)
                { 
                    *(I32 *)buf_tmp = (slot_num + 1);
                    currentSlot = slot_num;
                    *id = device_handle_request(REQUEST_EUTRAN_BBU_STATE, &dev_conf, buf, (I32 *)buf_tmp, dcode);
                    if (*id >= 0)
                    {
            	        cmd_queue_add(0, 0, TIMEOUT_CMD_QUEUE, *dcode, *id, 0);
                        timer_queue_add(TIMEOUT_CMD_NO_RSP, TIMER_ID_CMD_NO_RSP, 0, 0, 0, 0);
                    }
                }

                if (slot_num == LTE_CELL_NUM)
                {
                    slot_num = 0;
                    for (; slot_num < LTE_CELL_NUM; slot_num++)
                    {
                        if (dev_status.bbuStatus[slot_num].bbuState == BBU_LOCATION && (strcmp("TDD", dev_conf.capLte.lte[slot_num].desc) == 0))
                        break;
                    }
                    if (slot_num < LTE_CELL_NUM)
                    {
                        *(I32 *)buf_tmp = (slot_num + 1);
                        currentSlot = slot_num;                                      
                        *id = device_handle_request(REQUEST_EUTRAN_GET_BBU_SYNC, &dev_conf, buf, (I32 *)buf_tmp, dcode);
                        if (*id >= 0)
                        {
            	            cmd_queue_add(0, 0, TIMEOUT_CMD_QUEUE, *dcode, *id, 0);
                            timer_queue_add(TIMEOUT_CMD_NO_RSP, TIMER_ID_CMD_NO_RSP, 0, 0, 0, 0);
                        }
                    }
                }
                slot_num = 0;
                break;

           case IF_APP_BBU_SYNC_STATE:
 				rsp = (DEV_SET_RSP *) buf_tmp;
                timer_queue_del(TIMER_ID_CMD_NO_RSP);
                if(cmd_queue_del(rsp->dcode, rsp->id, socket, type) < 0) 
                {
                    cli_app_log(CLI_LOG_ERROR, "DEBUG get BBU info: CANNOT find command\n");
                }   
				if (rsp->code == PARA_VALUE_RESULT_SUCCESS)
                { 
                    slot_num = rsp->errcode;
                    slot_num--;
                    bbuStatus =(BBU_STATUS *)(buf_tmp + sizeof(DEV_SET_RSP));
                    dev_status.bbuStatus[slot_num].syncType = bbuStatus->syncType;
                    dev_status.bbuStatus[slot_num].syncState = bbuStatus->syncState;
                    if ((strcmp("TDD", dev_conf.capLte.lte[slot_num].desc) == 0))
                    {
                        if ((dev_status.bbuStatus[slot_num].syncState != INIT_SYNCED) && 
                            (dev_status.bbuStatus[slot_num].syncState != CNM_SYNCED) && 
                            (dev_status.bbuStatus[slot_num].syncState != GPS_SYNC) && 
                            (dev_status.bbuStatus[slot_num].syncState != GPS_INITALIZING))
                        {
                            dev_status.bbuStatus[slot_num].syncFialTm++;
                            cli_app_log(CLI_LOG_WARNING, "sync fialde bbu[%d] sync failed code [%d], nsyncTms [%d] \n",
                                        (slot_num + 1), dev_status.bbuStatus[slot_num].syncState, dev_status.bbuStatus[slot_num].syncFialTm);
                            if (cli_get_mng_status() == MNG_SERVER_STATUS_CONNECTED)
                            {
                                len = cmd_gen_warning((WR_BBU1_NSYNC + slot_num), buf, "");
                                cli_send_to_mng(buf, len);
                            }   
                            if ((timer_queue_find(TIMER_ID_REBOOT_BBU) < 0) && dev_status.bbuStatus[slot_num].syncFialTm >= 5 )
                            { 
                                cli_app_log(CLI_LOG_WARNING , "start time to reboot bbu\n");
                                //find bbu sync failed , so reboot it
                                timer_queue_add(TIMEOUT_REBOOT_BBU, TIMER_ID_REBOOT_BBU, 0, 0, 0, 0);
                            }
                        }
                    }
                    
                    slot_num++;
                }
                else if (*(I32 *) buf_tmp == PARA_VALUE_RESULT_DOING)
                { 
                    break; //last msg has no response, so break;                      
                }
                else
                { 
                    slot_num = (currentSlot + 1);
                }

                for (; slot_num < LTE_CELL_NUM; slot_num++)
                {
                    if (dev_status.bbuStatus[slot_num].bbuState == BBU_LOCATION && (strcmp("TDD", dev_conf.capLte.lte[slot_num].desc) == 0))
                    break;
                }                            

                if (slot_num < LTE_CELL_NUM)
                {
                    *(I32 *)buf_tmp = (slot_num + 1);
                    currentSlot = slot_num;
                    *id = device_handle_request(REQUEST_EUTRAN_GET_BBU_SYNC, &dev_conf, buf, (I32 *)buf_tmp, dcode);
                    if (*id >= 0)
                    {
            	        cmd_queue_add(0, 0, TIMEOUT_CMD_QUEUE, *dcode, *id, 0);
                        timer_queue_add(TIMEOUT_CMD_NO_RSP, TIMER_ID_CMD_NO_RSP, 0, 0, 0, 0);
                    }
                 }
             
                slot_num = 0;
                break;
               
           case IF_APP_EUTRAN_BBU_INFO:
				rsp = (DEV_SET_RSP *) buf_tmp;
                timer_queue_del(TIMER_ID_CMD_NO_RSP);
           
				if(cmd_queue_del(rsp->dcode, rsp->id, socket, type) < 0) 
				{
                	cli_app_log(CLI_LOG_ERROR, "DEBUG get BBU info: CANNOT find command\n");
                } 
                if (rsp->code == PARA_VALUE_RESULT_SUCCESS)
                {
                    if (cli_get_mng_status() == MNG_SERVER_STATUS_CONNECTED)
                    {
                        len = cmd_gen_bbu_info_string(&dev_conf, &dev_status, buf);
                        cli_send_to_mng(buf, len);
                    }                                              
                }
                else
                {
                    if (cli_get_mng_status() == MNG_SERVER_STATUS_CONNECTED)
                    {
                        len = cmd_gen_bbu_info_string(&dev_conf, &dev_status, buf);
                        cli_send_to_mng(buf, len);
                    }
                }
                 
                break;
            
           case IF_APP_SR_EUTRAN_VERSION:
				rsp = (DEV_SET_RSP *) buf_tmp;
                Info = (SOFTWARE_VERSION_INFO *)(buf_tmp + sizeof(DEV_SET_RSP));
                timer_queue_del(TIMER_ID_CMD_NO_RSP);
           
				if(cmd_queue_del(rsp->dcode, rsp->id, socket, type) < 0) 
				{
                	cli_app_log(CLI_LOG_ERROR,"DEBUG get Eutran soft version info: CANNOT find command\n");
                } 

                if (cli_get_mng_status() == MNG_SERVER_STATUS_CONNECTED)
                {
                    if (rsp->code == PARA_VALUE_RESULT_SUCCESS)
                    {
                        len = cmd_gen_bbu_version(buf, Info->software_version, Info->slotId);
                    }
                    else
                    {
                        len = cmd_gen_mng_response(buf, BUFFER_BLOCK_SIZE, RST_FAILED,
                                               device_get_error_string (rsp->errcode), *fcode, *type, cmdList);
                    }
                    cli_send_to_mng(buf, len);

                }
  
                break;
            default:
                //save to config, todo: debug it.
                if (xml_handle_conf ((I8 *) (buf_tmp + (sizeof(DEV_SET_RSP))), conf_req) != REQUEST_UPDATA_NONE) 
			    {
                      //todo: if we need gen config chagne to server.
			    }
                
                break;
        }
    } 
	else if (conf_req & RESPONSE_IND_RESPONSE) 
	{
        switch (conf_req & RESPONSE_TYPE_MASK) 
		{
            case IF_APP_DATA_CONTINUE:
                if (atoi(dev_conf.dev.uploadMode) == 2)
                {
                    if (updata->num <= atoi(dev_conf.ftp.ftpmaxcount)) 
                    {
                        len = 0;
                        saveFtpdata(updata, (PHONE_TMP *)buf_tmp, &len);

                        if (len == 0) 
                        {
                            //no phone data in this frame, send ack to get next one.
                            device_handle_request (REQUEST_UPDATA_IND_ACK, &dev_conf, buf, NULL, NULL);
                            break;
                        }

                        if (updata->num == atoi(dev_conf.ftp.ftpmaxcount) && fileIsFull()) 
                        {
                            cli_app_log(CLI_LOG_INFO, "DEBUG UPDATA: upload data %d, len %d\n",
                                    updata->num, updata->len);


                            //send cache full ,send it.
                            if (up_time[0] != up_time[1]) 
                            {
                                if (uploadFile())
                                    timer_queue_add(CLI_APP_1S,  TIMER_ID_FTP_UPLOAD_STATE, 0, 0, 0, 0);
                                //save endtime.
                                up_time[2] = updata->time + 1;
                            } 
                            else 
                            {
                                if (uploadFile())
                                    timer_queue_add(CLI_APP_1S,  TIMER_ID_FTP_UPLOAD_STATE, 0, 0, 0, 0);
                            }

                            //clear buffer
                            memset(updata->data, 0 , updata->len);
                            updata->num = 0;
                            updata->len = 0;
                            updata->time = 0;
                            //set timeout,

                            //sent stop.
                            device_handle_request(REQUEST_UPDATA_STOP, &dev_conf, buf, NULL, NULL);

                            //clear cmd queue.                                      
                            if (cmd_queue_del(*dcode, *id, socket, type) < 0) 
                            {
                                cli_app_log(CLI_LOG_ERROR, "DEBUG UPDATA: CANNOT find command\n");
                            }

                            //then store remaining data to this buffer.
                            saveFtpdata(updata, (PHONE_TMP *)buf_tmp, &len);

                            //there is data in this device message, save new time.
                            if(updata->time != 0) 
                            {
                                up_time[2] = updata->time + 1;
                                // that means end of send historical data;
                            }
                        } 
                        else 
                        {
                            device_handle_request(REQUEST_UPDATA_IND_ACK, &dev_conf, buf, NULL, NULL);
                        }
                    } 
                    else 
                    {
                        cli_app_log(CLI_LOG_ERROR,"DEBUG UPDATA: should not go here, SYNC\n");
                    }
                }
                else
                {
                    if (updata->num < MAX_DATA_PER_FRAME) 
                    {
                        len = cmd_gen_data_upload(updata, (PHONE_TMP *)buf_tmp, 0);

                        if (len == 0) 
                        {
                            //no phone data in this frame, send ack to get next one.
                            device_handle_request (REQUEST_UPDATA_IND_ACK, &dev_conf, buf, NULL, NULL);
                            break;
                        }

                        if (updata->num == MAX_DATA_PER_FRAME) 
                        {
                            cli_app_log(CLI_LOG_INFO, "DEBUG UPDATA: upload data %d, len %d\n",
                                    updata->num, updata->len);

                            if (*addDevNum == 1)  cmd_gen_data_upload_end(updata, dev_conf.dev.devNum);

                            //send cache full ,send it.
                            if (up_time[0] != up_time[1]) 
                            {
                                cli_send_to_data(updata->data, updata->len);
                                //save endtime.
                                up_time[2] = updata->time + 1;
                            } 
                            else 
                            {
                                cli_send_to_data(updata->data, updata->len);
                            }

                            //clear buffer
                            memset(updata->data, 0 , updata->len);
                            updata->num = 0;
                            updata->len = 0;
                            updata->time = 0;
                            //set timeout,
                            fd_times++;

                            timer_queue_add(TIMEOUT_UPDATA_FB(atoi(dev_conf.data.itvl)),
                                    TIMER_ID_SYNC_FEEDBACK,
                                    0, 0, 0, 0);

                            //sent stop.
                            device_handle_request(REQUEST_UPDATA_STOP, &dev_conf, buf, NULL, NULL);

                            //clear cmd queue.                                      
                            if (cmd_queue_del(*dcode, *id, socket, type) < 0) 
                            {
                                cli_app_log(CLI_LOG_ERROR, "DEBUG UPDATA: CANNOT find command\n");
                            }

                            //then store remaining data to this buffer.
                            cmd_gen_data_upload(updata, (PHONE_TMP *) buf_tmp, len);

                            //there is data in this device message, save new time.
                            if(updata->time != 0) 
                            {
                                if (historical_data == 0)
                                    up_time[2] = updata->time + 1;
                                else          
                                    historical_time[0] = updata->time + 1;
                            }
                        } 
                        else 
                        {
                            device_handle_request(REQUEST_UPDATA_IND_ACK, &dev_conf, buf, NULL, NULL);
                        }
                    } 
                    else 
                    {
                        cli_app_log(CLI_LOG_ERROR,"DEBUG UPDATA: should not go here, SYNC\n");
                    }

                }

                break;
            case IF_APP_DATA_END:     
                if (atoi(dev_conf.dev.uploadMode) == 2)
                {
                    if (updata->num <= atoi(dev_conf.ftp.ftpmaxcount)) 
                    {                      
                        len = 0;
                        saveFtpdata(updata, (PHONE_TMP *)buf_tmp, &len);

                        if (updata->num > 0) 
                        {
                            // cmd_gen_data_upload_end(updata);
                            cli_app_log(CLI_LOG_INFO, "DEBUG UPDATA: upload data %d, len %d\n",updata->num, updata->len);

                            //last frame, sent it.
                            if (up_time[0] != up_time[1]) 
                            {
                                if (uploadFile())
                                    timer_queue_add(CLI_APP_1S,  TIMER_ID_FTP_UPLOAD_STATE, 0, 0, 0, 0);
                                //save endtime.
                                up_time[2] = updata->time + 1;
                            } 
                            else 
                            {
                                //todo: verify wait feed back from mng server.
                                if (uploadFile())
                                    timer_queue_add(CLI_APP_1S,  TIMER_ID_FTP_UPLOAD_STATE, 0, 0, 0, 0);
                            }

                            //clear buffer
                            memset(updata->data, 0, updata->len);
                            updata->num = 0;
                            updata->len = 0;
                            updata->time = 0;
                            //set timeout,

                            //clear cmd queue.                                      
                            if (cmd_queue_del(*dcode, *id, socket, type) < 0) 
                            {
                                cli_app_log(CLI_LOG_ERROR, "DEBUG UPDATA: CANNOT find command\n");
                            }

                            //then store remaining data to this buffer.
                            saveFtpdata(updata, (PHONE_TMP *)buf_tmp, &len);

                            //there is data in this device message, save new time.
                            if(updata->time != 0) 
                            {
                                up_time[2] = updata->time + 1;
                                // that means end of send historical data;
                            }
                        } 	
                        else 
                        {
                            //we did not get any data, keep these 2 time as the same
                            //to make sure data correct if mng server want to get data.

                            //note, we should not jump to next time peroid.
                            //Here might be some optimization to make device side does not eat too many mips
                            // up_time[0] = up_time[1];

                            up_time[0] = up_time[1] = up_time[2];
                            //clear cmd queue.       
                            timer_queue_del(TIMER_ID_CMD_NO_RSP);                               
                            if (cmd_queue_del(*dcode, *id, socket, type) < 0) 
                            {
                                cli_app_log(CLI_LOG_ERROR, "DEBUG UPDATA: CANNOT find command\n");
                            }
                        }
                    } 
                    else 
                    {
                        cli_app_log(CLI_LOG_ERROR, "DEBUG UPDATA: should not go here SYNC_F\n");
                    }
                }
                else
                {
                    if (updata->num < MAX_DATA_PER_FRAME) 
                    {                      
                        len = cmd_gen_data_upload(updata, (PHONE_TMP *)buf_tmp, 0);

                        if (updata->num > 0) 
                        {
                            // cmd_gen_data_upload_end(updata);
                            cli_app_log(CLI_LOG_INFO, "DEBUG UPDATA: upload data %d, len %d\n",updata->num, updata->len);

                            if (*addDevNum == 1)
                                cmd_gen_data_upload_end(updata, dev_conf.dev.devNum);

                            //last frame, sent it.
                            if (up_time[0] != up_time[1]) 
                            {
                                cli_send_to_data(updata->data, updata->len);
                                //save endtime.
                                up_time[2] = updata->time + 1;
                            } 
                            else 
                            {
                                //todo: verify wait feed back from mng server.
                                cli_send_to_data(updata->data, updata->len);
                                if (*historical_data != 0)
                                    *historical_data = 2;
                            }

                            //clear buffer
                            memset(updata->data, 0, updata->len);
                            updata->num = 0;
                            updata->len = 0;
                            updata->time = 0;
                            //set timeout,
                            fd_times++;
                            timer_queue_add(TIMEOUT_UPDATA_FB(atoi(dev_conf.data.itvl)),
                                    TIMER_ID_SYNC_FEEDBACK,
                                    0, 0, 0, 0);

                            //clear cmd queue.                                      
                            if (cmd_queue_del(*dcode, *id, socket, type) < 0) 
                            {
                                cli_app_log(CLI_LOG_ERROR, "DEBUG UPDATA: CANNOT find command\n");
                            }

                            //then store remaining data to this buffer.
                            cmd_gen_data_upload(updata, (PHONE_TMP *)buf_tmp, len);

                            //there is data in this device message, save new time.
                            if(updata->time != 0) 
                            {
                                if (historical_data == 0)
                                    up_time[2] = updata->time + 1;
                                else 
                                    historical_data = 0; 
                                // that means end of send historical data;
                            }
                        } 	
                        else 
                        {
                            //we did not get any data, keep these 2 time as the same
                            //to make sure data correct if mng server want to get data.

                            //note, we should not jump to next time peroid.
                            //Here might be some optimization to make device side does not eat too many mips
                            // up_time[0] = up_time[1];

                            up_time[0] = up_time[1] = up_time[2];
                            //clear cmd queue.       
                            timer_queue_del(TIMER_ID_CMD_NO_RSP);                               
                            if (cmd_queue_del(*dcode, *id, socket, type) < 0) 
                            {
                                cli_app_log(CLI_LOG_ERROR, "DEBUG UPDATA: CANNOT find command\n");
                            }
                        }
                    } 
                    else 
                    {
                        cli_app_log(CLI_LOG_ERROR, "DEBUG UPDATA: should not go here SYNC_F\n");
                    }
                }
                break;

            case IF_APP_BLACKLIST_END:
            case IF_APP_BLACKLIST_CONTINUE:
                if (strcmp(dev_conf.dev.protocol, XINAN) == 0)
                {
                    len = packBlackList(buf, (PHONE_TMP *)buf_tmp);
                    cli_send_to_mng(buf, len);
                }
                if ((conf_req & RESPONSE_TYPE_MASK) == IF_APP_BLACKLIST_CONTINUE)
                {
                    device_handle_request(REQUEST_SR_BLACKLIST_INACK, &dev_conf, buf, NULL, NULL);
                }
                else
                {
                    device_handle_request(REQUEST_SR_BLACKLIST_STOP, &dev_conf, buf, NULL, NULL);
                    if (cmd_queue_del(*dcode, *id, socket, type) < 0) 
                    {
                        cli_app_log(CLI_LOG_ERROR, "DEBUG UPDATA: CANNOT find command\n");
                    }
                }
                   
                break;    

            case IF_APP_DATA_EVENT:
                if ((atoi(dev_conf.dev.uploadMode) == 2) || strcmp(dev_conf.dev.protocol, LOCATION) == 0)
                {
                    if (cli_get_data_status() == DATA_SERVER_STATUS_CONNECTED)
                    {
                        len = pack_ftp_current_data(buf, (PHONE_TMP *)buf_tmp);
                        cli_send_to_data(buf, len);
                    }
                }
                else
                {
                    if (strcmp(dev_conf.dev.protocol, ZHONGDUN) != 0)
                        handle_recv_data((PHONE_TMP *)buf_tmp);
                    else
                        handle_zhongdun_data((PHONE_TMP *)buf_tmp);
                }
                break;

            case IF_APP_MAC_EVENT:
                 handle_recv_mac_data((PHONE_TMP *)buf_tmp);
                 break;

            case IF_APP_SNF_RSLT:                               
                 if (*((I32 *) buf_tmp + 1) >= 0) 
                 {
                     len = cmd_gen_snf_result(SNF_RESULT_AUTO, buf, ((I32 *) buf_tmp));
                 }

                 if (cli_get_mng_status() == MNG_SERVER_STATUS_CONNECTED)
                     cli_send_to_mng(buf, len);

                 break;
            case IF_APP_BBU_STATE:
                slot_num = *(I32 *)buf_tmp - 1;
                bbuRp = *((I32 *) buf_tmp + 1);

                if (dev_status.bbuStatus[slot_num].bbuState != BBU_INIT_CFG)
                {
                    if (bbuRp == BBU_LOCATION)
                    {
                        dev_status.bbuStatus[slot_num].bbuState = bbuRp; 
                        if (cli_get_mng_status() == MNG_SERVER_STATUS_CONNECTED)
                        {
                             len = cmd_gen_bbu_info_string(&dev_conf, &dev_status, buf);
                             cli_send_to_mng(buf, len);
                        }    
                        if ((strcmp("FDD", dev_conf.capLte.lte[slot_num].desc) == 0))
                            dev_status.bbuStatus[slot_num].syncState = CNM_SYNCED;
                    }
                    else if ((dev_status.bbuStatus[slot_num].bbuState == BBU_LOCATION) && (bbuRp) == BBU_CELL_CFG)
                    {    
                        cli_app_log(CLI_LOG_INFO, "recevice bbu location before cell_cfg so drop it\n");
                    }         
                    else
                    {
                        if ((dev_status.bbuStatus[slot_num].bbuState == BBU_UPGRADING) && (bbuRp == BBU_REDAY))
                             cmd_queue_del(*dcode, *id, socket, type);
                        if (dev_status.bbuStatus[slot_num].bbuState < BBU_UPGRADE)
                            dev_status.bbuStatus[slot_num].bbuState = bbuRp;
                    }           
                }

                cli_app_log(CLI_LOG_INFO, "bbu[%d] state is %d \n", slot_num, bbuRp);
                if (bbuRp == BBU_INACTIVE )
                {
                    if (cli_get_mng_status() == MNG_SERVER_STATUS_CONNECTED)
                    {
                        //len = cmd_gen_warning((WR_BBU_HEARTBEAT_BBU1 + slot_num), buf, "");
                        //cli_send_to_mng(buf, len);
                    }
                    dev_status.realTimeStatus[slot_num].isActive = 0;
                    dev_status.bbuStatus[slot_num].syncState = NOT_START;
                }
                else
                {
                    if (bbuRp == BBU_LOCATION)
                    {
                        dev_status.realTimeStatus[slot_num].isActive = 2;
                    }
                    else
                    {
                        dev_status.realTimeStatus[slot_num].isActive = 1;
                    }
                }

                if (bbuRp == BBU_REDAY ) //if bbu state == 2 means  bbu ready
                {
                    if ((dev_status.bbuStatus[slot_num].bbuState != BBU_UPGRADE) && (dev_status.bbuStatus[slot_num].bbuState != BBU_UPGRADING))
                    {
                        dev_status.bbuStatus[slot_num].bbuState =bbuRp;
                        if (timer_queue_find(TIMER_ID_BBU_CONFIG_CELL) < 0) 
                             timer_queue_add(TIMEOUT_BBU_CONFIG_CELL, TIMER_ID_BBU_CONFIG_CELL, 0, 0, 0, 0);
                    }
                    if ((dev_status.bbuStatus[slot_num].bbuState== BBU_UPGRADING) && (bbuRp == BBU_REDAY))
                    {
                        upgradeFailTm++;
                        cmd_queue_del(CMD_CODE_EUTRAN_BBU_UPGRADE, *id, socket, type);
                        if (timer_queue_find(TIMER_ID_RESTART_UPGRADE_BBU) < 0)
                            timer_queue_add(TIMEOUT_RESTART_UPGRADE_BBU, TIMER_ID_RESTART_UPGRADE_BBU, 0, 0, 0, 0);
                    }
                }
          
                slot_num = 0;
                break;

            case IF_APP_GSM_SNIFF:
                len = cmd_gen_gsm_sniff_result(buf, buf_tmp);  
                if (cli_get_mng_status() == MNG_SERVER_STATUS_CONNECTED)  
                {  
                    cli_send_to_mng(buf, len);
                }
                if (strcmp(dev_conf.dev.protocol, ZHONGDUN) == 0)
                {
                    cli_send_to_data(buf, len);
                }
                break;

            case CMD_WCDMA_EVT_SNIFF:
            case CMD_LTE_EVT_SNIFF:
                len = cmd_gen_gsm_sniff_result(buf, buf_tmp);  
                if (cli_get_mng_status() == MNG_SERVER_STATUS_CONNECTED)  
                {
                    cli_app_log(CLI_LOG_NOTICE, "sniffer is %s \n", buf);
                    cli_send_to_mng(buf, len);
                }

                break;

                //warnings...
            case CMD_CODE_BLACKLIST_ALERT:
                len = cmd_gen_blackList(buf, (PHONEINFO *)buf_tmp);
                if (cli_get_mng_status() == MNG_SERVER_STATUS_CONNECTED)    
                    cli_send_to_mng(buf, len);
                break;

			case CMD_EVT_EUTRAN_NMM_DELAY_REPORT:
				if (cli_get_mng_status() == MNG_SERVER_STATUS_CONNECTED)
				{
					len = cmd_gen_delay_report(buf, (DELAY_REPORT *)buf_tmp);
					cli_send_to_mng(buf, len);

				}
				break;
#if 0
            case CMD_EVT_ALARM_PA_SWR:
                len = cmd_gen_warning(WR_VSWR, buf, device_get_error_string(conf_req & RESPONSE_TYPE_MASK));
                if (cli_get_mng_status() == MNG_SERVER_STATUS_CONNECTED)
                    cli_send_to_mng(buf, len);
                break;

            case CMD_EVT_ALARM_PA_FAULT_PA:
            case CMD_EVT_ALARM_PA_FAULT_LNA:
                if (cli_get_mng_status() == MNG_SERVER_STATUS_CONNECTED)
                {
                    len = cmd_gen_warning(WR_RF_MODULE, buf, device_get_error_string(conf_req & RESPONSE_TYPE_MASK));
                    cli_send_to_mng(buf, len);
                }
                break;

            case CMD_EVT_ALARM_PA_OVER_TEMP:
                if (cli_get_mng_status() == MNG_SERVER_STATUS_CONNECTED)
                {
                    len = cmd_gen_warning(WR_PA_HIGH_TEMP, buf, device_get_error_string(conf_req & RESPONSE_TYPE_MASK));
                    cli_send_to_mng(buf, len);
                }
                break;
#endif
            case CMD_EVT_ALARM_PM_POWER_OFF:
                if (cli_get_mng_status() == MNG_SERVER_STATUS_CONNECTED)
                {
                    cli_app_log(CLI_LOG_WARNING, "device power is off \n");
                    len = cmd_gen_warning(WR_POWEROFF, buf, "");
                    cli_send_to_mng(buf, len);   
                }
                break;


            case CMD_EVT_ALARM_PM_DOOR_OPEN:
                if (cli_get_mng_status() == MNG_SERVER_STATUS_CONNECTED)
                {
                    len = cmd_gen_warning(WR_DEV_BOX_OPEN, buf, device_get_error_string(conf_req & RESPONSE_TYPE_MASK));
                    cli_send_to_mng(buf, len);   
                }
                break;

            case CMD_EVT_ALARM_PM_GRAND_LOST:
                if (cli_get_mng_status() == MNG_SERVER_STATUS_CONNECTED)
                {
                    len = cmd_gen_warning(WR_DEV_LINE_BREAK, buf, device_get_error_string(conf_req & RESPONSE_TYPE_MASK));
                    cli_send_to_mng(buf, len);
                }   
                break;

            case CMD_EVT_ALARM_SMS_TASK_DOWN:
                cli_app_log(CLI_LOG_WARNING, "open 3g AT interface failed, please check 3g hardware\n");
                break;

            case CMD_CODE_SYSMONITOR_HEARTBEAT:
                timer_queue_update(TIMER_ID_DEV_DEAD, TIMEOUT_DEV_DEAD(atoi(dev_conf.mng.itvl)));
                cli_app_log(CLI_LOG_INFO, "recv heart beat from sysMonitor \n");
                break;
        
            case CMD_GSM_EVT_SYNC:
                cli_app_log(CLI_LOG_NOTICE, "gsm module  is running \n");
                dev_status.realTimeStatus[7].isActive = 1;
                dev_status.realTimeStatus[8].isActive = 1;
                break;                

            case CMD_GSM_EVT_NSYNC:
                cli_app_log(CLI_LOG_WARNING, "gsm module lost hearbeat \n");
                dev_status.realTimeStatus[7].isActive = 0;
                dev_status.realTimeStatus[8].isActive = 0;
                if (cli_get_mng_status() == MNG_SERVER_STATUS_CONNECTED)
                {
                    len = cmd_gen_warning(WR_BBU_HEARTBEAT_GSM, buf, "");
                    cli_send_to_mng(buf, len);
                }   
                break;

            case CMD_CDMA_EVT_NSYNC:
                dev_status.realTimeStatus[9].isActive = 0;
                cli_app_log(CLI_LOG_WARNING, "cdma module lost hearbeat \n");
                if (cli_get_mng_status() == MNG_SERVER_STATUS_CONNECTED)
                {
                    len = cmd_gen_warning(WR_BBU_HEARTBEAT_CDMA, buf, "");
                    cli_send_to_mng(buf, len);
                }   
                break;


            case CMD_CDMA_EVT_SYNC:
                cli_app_log(CLI_LOG_NOTICE, "cdma module is running\n");
                dev_status.realTimeStatus[9].isActive = 1;
                break;

            case CMD_WCDMA_EVT_NSYNC:
                dev_status.realTimeStatus[10].isActive = 0;
                cli_app_log(CLI_LOG_WARNING, "wcdma module lost hearbeat \n");
                if (cli_get_mng_status() == MNG_SERVER_STATUS_CONNECTED)
                {
                    len = cmd_gen_warning(WR_BBU_HEARTBEAT_WCDMA, buf, "");
                    cli_send_to_mng(buf, len);
                }   
                break;
             
            case CMD_WCDMA_EVT_SYNC:
                dev_status.realTimeStatus[10].isActive = 1;
                cli_app_log(CLI_LOG_NOTICE, "wcdma module is running\n");
                break;
                
            case CMD_TDSCDMA_EVT_NSYNC:
                dev_status.realTimeStatus[11].isActive = 0;
                cli_app_log(CLI_LOG_WARNING, "tdscdma module lost hearbeat \n");
                if (cli_get_mng_status() == MNG_SERVER_STATUS_CONNECTED)
                {
                    len = cmd_gen_warning(WR_BBU_HEARTBEAT_TDSCDMA, buf, "");
                    cli_send_to_mng(buf, len);
                }   
                break;

            case CMD_TDSCDMA_EVT_SYNC:
                dev_status.realTimeStatus[11].isActive = 1;
                cli_app_log(CLI_LOG_NOTICE, "tdscdma module is running \n");
                break;

            case CMD_GSM_EVT_NOT_RECV_IMSI:
                cli_app_log(CLI_LOG_WARNING, "gsm module can not recv imsi \n");
                if (cli_get_mng_status() == MNG_SERVER_STATUS_CONNECTED)
                {
                    len = cmd_gen_warning(WR_GSM_NOT_RECV_IMSI, buf, "");
                    cli_send_to_mng(buf, len);
                }   
                break;
                
            case CMD_CDMA_EVT_NOT_RECV_IMSI:
                cli_app_log(CLI_LOG_WARNING, "cdma module can not recv imsi \n");
                if (cli_get_mng_status() == MNG_SERVER_STATUS_CONNECTED)
                {
                    len = cmd_gen_warning(WR_CDMA_NOT_RECV_IMSI, buf, "");
                    cli_send_to_mng(buf, len);
                }   
                break;

            case CMD_WCDMA_EVT_NOT_RECV_IMSI:
                cli_app_log(CLI_LOG_WARNING, "wcdma module can not recv imsi \n");
                if (cli_get_mng_status() == MNG_SERVER_STATUS_CONNECTED)
                {
                    len = cmd_gen_warning(WR_WCDMA_NOT_RECV_IMSI, buf, "");
                    cli_send_to_mng(buf, len);
                }   
                break;

            case CMD_TDSCDMA_EVT_NOT_RECV_IMSI:
                cli_app_log(CLI_LOG_WARNING, "tdscdma module can not recv imsi \n");
                if (cli_get_mng_status() == MNG_SERVER_STATUS_CONNECTED)
                {
                    len = cmd_gen_warning(WR_TDSCDMA_NOT_RECV_IMSI, buf, "");
                    cli_send_to_mng(buf, len);
                }   
                break;


            case CMD_EVT_EUTRAN_NOT_RECV_IMSI:
                slot_num = *(I32 *)buf_tmp - 1;
                if (cli_get_mng_status() == MNG_SERVER_STATUS_CONNECTED)
                {
                    len = cmd_gen_warning((WR_BBU1_NOT_RECV_IMSI + slot_num), buf, "");
                    cli_send_to_mng(buf, len);
                }   
                break;



            case CMD_GSM_EVT_LOST:
                cli_app_log(CLI_LOG_WARNING, "gsm module lost \n");
                if (cli_get_mng_status() == MNG_SERVER_STATUS_CONNECTED)
                {
                    len = cmd_gen_warning(WR_GSM_LOST, buf, "");
                    cli_send_to_mng(buf, len);
                }   
                break;
                
            case CMD_CDMA_EVT_LOST:
                cli_app_log(CLI_LOG_WARNING, "cdma module lost \n");
                if (cli_get_mng_status() == MNG_SERVER_STATUS_CONNECTED)
                {
                    len = cmd_gen_warning(WR_CDMA_LOST, buf, "");
                    cli_send_to_mng(buf, len);
                }   
                break;

            case CMD_WCDMA_EVT_LOST:
                cli_app_log(CLI_LOG_WARNING, "wcdma module lost \n");
                if (cli_get_mng_status() == MNG_SERVER_STATUS_CONNECTED)
                {
                    len = cmd_gen_warning(WR_WCDMA_LOST, buf, "");
                    cli_send_to_mng(buf, len);
                }   
                break;

            case CMD_TDSCDMA_EVT_LOST:
                cli_app_log(CLI_LOG_WARNING, "tdscdma module lost \n");
                if (cli_get_mng_status() == MNG_SERVER_STATUS_CONNECTED)
                {
                    len = cmd_gen_warning(WR_TDSCDMA_LOST, buf, "");
                    cli_send_to_mng(buf, len);
                }   
                break;


            case CMD_EVT_EUTRAN_BBU_LOST:
                slot_num = *(I32 *)buf_tmp - 1;
                if (cli_get_mng_status() == MNG_SERVER_STATUS_CONNECTED)
                {
                    len = cmd_gen_warning((WR_BBU1_LOST + slot_num), buf, "");
                    cli_send_to_mng(buf, len);
                }   
                break;


            case CMD_EVT_ALARM_PA_SWR:
                len = cmd_gen_warning((WR_PA1_SWR_WARN + *(I32 *)buf_tmp), buf, "");
                if (cli_get_mng_status() == MNG_SERVER_STATUS_CONNECTED)
                    cli_send_to_mng(buf, len);
                break;

            case CMD_EVT_ALARM_PA_OVER_TEMP:
                len = cmd_gen_warning((WR_PA1_TEMP_WARN + *(I32 *)buf_tmp), buf, device_get_error_string(CMD_EVT_ALARM_PA_OVER_TEMP));
                if (cli_get_mng_status() == MNG_SERVER_STATUS_CONNECTED)
                    cli_send_to_mng(buf, len);
                break;

            case CMD_CODE_GPS_ALERT_INFO:
                position = (GPSPOSITION *)buf_tmp;
                if (cli_get_mng_status() == MNG_SERVER_STATUS_CONNECTED)
                {
                    len = cmd_gen_warning_with_data(WR_DEV_GPS, buf, buf_tmp);
                    cli_send_to_mng(buf, len);
                }   
                cli_app_log(CLI_LOG_WARNING, "device moving gspinfo longitude:%f latitude:%f \n", position->longitude, position->latitude);
                break;

            case CMD_EVT_ALARM_PM_POWER_ON:
                if (cli_get_mng_status() == MNG_SERVER_STATUS_CONNECTED)
                {
                    cli_app_log(CLI_LOG_WARNING, "device power is on \n");
                    len = cmd_gen_warning(WR_DEV_POWER_ON, buf, "");
                    cli_send_to_mng(buf, len);   
                }
                break;

            case CMD_GSM_EVT_CONFIG:
                {
                    GSM_PAR *gsmConf = (GSM_PAR *)buf_tmp;
                    if (gsmConf->carrier == 0)
                    {
                        dev_status.realTimeStatus[7].lac = gsmConf->lac;
                        dev_status.realTimeStatus[7].freq = gsmConf->bcc;
                        cli_app_log(CLI_LOG_DEFAULT, "carrier 0 lac %d freq %d \n",  gsmConf->lac,  gsmConf->bcc);
                    }
                    else if (gsmConf->carrier == 1)
                    {
                        dev_status.realTimeStatus[8].lac = gsmConf->lac;
                        dev_status.realTimeStatus[8].freq = gsmConf->bcc;
                        cli_app_log(CLI_LOG_DEFAULT, "carrier 1 lac %d freq %d \n",  gsmConf->lac,  gsmConf->bcc);

                    }
                    
                }
                break;

            case CMD_EVT_EUTRAN_REPORT_BBU_EARFCN:
                {
                    I32 slotId = *(I32 *)buf_tmp -1;
                    U16 earfcn = *((I32 *) buf_tmp + 1);
                    dev_status.realTimeStatus[slotId].freq = earfcn;
                    cli_app_log(CLI_LOG_NOTICE, "slotId %d using earfcn %d \n", slotId, earfcn);
                }


#ifdef MODULE_TEST
            case CMD_CODE_SYSMONITOR_TEST_MODULE:
                if ( *(I32 *)buf_tmp == PARA_VALUE_SYSMONITOR_MAIN )
                {
                    cli_app_log(CLI_LOG_INFO, "----- test module system ----- %04x\n", CMD_CODE_SYSMONITOR_TEST_MODULE);
                    while(1)
                    {
     
                    }
                }
                else if ( *(I32 *)buf_tmp == PARA_VALUE_SYSMONITOR_THREAD1 )   
                {
                    setTestCliThread();
                } 
                else if ( *(I32 *)buf_tmp == PARA_VALUE_SYSMONITOR_THREAD2 )   
                {
                    setTestMsgrcv();
                }                           
                break; 
#endif
             
             case CMD_CODE_FEP_LOG_LEVEL:
                 if(*(I32 *)buf_tmp == CMD_SET_LOG_LEVEL)
                 {
					  //set cmd log level by cli. para is the log level(0-7) only
				      //use socket as tmp parameter.

                      *socket = *(I32 *) (buf_tmp + 4);
                      if(*socket != 4) 
                      {
                          cli_app_log(CLI_LOG_ERROR, "Get set log level command from device with wrong len\n");
                      }
                      
                      *socket = *(I32 *) (buf_tmp + 8); 
                      if(*socket > 7 || *socket < 1) 
                      {
                          cli_app_log(CLI_LOG_ERROR, "Get set log level command from device with wrong len\n");
                      }
						  
                      log_level = *socket;
                      cli_app_log(CLI_LOG_CRITICAL, "Set log level to %d\n", log_level);
					              device_handle_fep_response(buf_tmp);
				 }
                 else
                 {
                     cli_app_log(CLI_LOG_ERROR, "Wrong command for FEP LOG Level setting. \n");
                 }

				 break;
             case CMD_CODE_FEP_UPGRADE:
                 *id = device_handle_request(REQUEST_SOFTWARE_UPDATA, &dev_conf, buf, (I32 *)buf_tmp, dcode);                                  
                 if (*id >= 0) 
				 {
             	     cmd_queue_add(0, 0, TIMEOUT_CMD_QUEUE, *dcode, *id, 1);
                     timer_queue_add(TIMEOUT_CMD_NO_RSP, TIMER_ID_CMD_NO_RSP, 0, 0, 0, 0);
                     cli_app_log(CLI_LOG_INFO, "----------------no rsp add -------------\n");
                 }
                    
                 break;          
             default:
                 //other warning... no special warning code, ignore them.
                 break;
         }
     } 
     else if (conf_req & RESPONSE_SET_CONTINUE) 
     {
         rsp = (DEV_SET_RSP *) buf_tmp;
         //have to do so......need change it if there is better idea.
         if ((*fcode = cmd_queue_del(rsp->dcode, rsp->id, socket, type)) >= 0)
         {
             cmd_queue_add(*fcode, *socket, TIMEOUT_CMD_QUEUE, rsp->dcode, rsp->errcode, *type);
         }
         else
         {
             cli_app_log(CLI_LOG_ERROR, "CMD_QUEUE ERROR: can not find command\n");
         }
     }
     
     buffer_free(buf_tmp);
     buffer_free(buf);

     return;    
}

static void *cli_app_event_handler(void *argv)
{
    pthread_setname_np(pthread_self(), "handle_thread");
    I8 *buf, *buf_tmp, *msg_tmp = NULL;
    I32 buf_len = 0, len = 0 , tmp_len = 0 , historical_data = 0;
    I32 fcode, dcode = 0, id = 0;
    I32 cli_req, conf_req;
    DEV_SET_RSP *rsp; 
    srvcmd = malloc(DEV_INFO_ADD_LEN);
    I32 socket = 0, addDevNum = 0;
    I32 type = 0; //is this cmdType
    I32 cli_rst_times = 0 ;
    UPDATA_CACHE *updata = (UPDATA_CACHE *) up_cache;
	updata->num = 0;
    updata->len = 0;
    updata->time = 0;
    time(&up_time[1]);  
    up_time[2] = up_time[0] = atoi(dev_conf.ftp.ftpuptime);
    idle_time[0] = idle_time[1] = 0;
    I32 autoslot[CELL_NUM] = {0};     
    I32 slot_num = 0, serialnum = 0, manual_times = 0; //it is a flag to count slot
    static I32 setautosnf[CELL_NUM] = {0};
    serialnum = up_time[1];//let serialnum to current time 
    I32 numRcv[CELL_NUM] = {0, 0, 0, 0, 0, 0, 0};//it is a flag to judge whether recevice reponse from service
    memset(srvcmd, 0, DEV_INFO_ADD_LEN);
    UPLOADLIST *uploadList = NULL;
    while (1) 
    {
        sem_wait(&sem_main);
        while (event_queue_e != event_queue_s) 
        {
            if (IF_APP_EVENT_TIMER != event_queue[event_queue_e].module)
            {
                cli_app_log(CLI_LOG_INFO, "-------------------rcv event :%08x, socket is %08x commadListNum is %d\n",
							event_queue[event_queue_e].module,
                           	event_queue[event_queue_e].socket, cmdList.commandNum);
            }
			
            switch (event_queue[event_queue_e].module) 
            {
                case IF_APP_EVENT_INIT_DEV:
                    //dump init msg for debuging
                     cli_app_log(CLI_LOG_INFO, "rcv device init msg, len is %d: \n",	buf_len);
                     buffer_dump_log(buf, buf_len, CLI_LOG_DEFAULT);

                    if ((buf = event_queue[event_queue_e].data) == NULL || (buf_len = event_queue[event_queue_e].len) == 0) 
                    {
		                //start interface and rcv thread.
                        //device_interface_init();
                        //first command.
                        if (device_get_init_status() == DEV_INIT_STAT_DISCONNECT) 
                        {
                            device_interface_init();
							
                            if ((buf_tmp = buffer_allocate()) == NULL) 
                            {
                                 cli_app_log(CLI_LOG_CRITICAL, "cli_main: get buffer fail\n");
                                 break;
                            }
							
                           	//start first command.
                            id = device_handle_init_all(&dev_conf, buf_tmp, &dcode);

                           	//should not happen, or break out and hung at main thread.
                            if (id != IF_APP_ERROR) 
                            {
                                cmd_queue_add(0, 0, TIMEOUT_CMD_QUEUE, dcode, id, 0);
                                //timer_queue_add(TIMEOUT_CMD_NO_RSP, TIMER_ID_CMD_NO_RSP, 0, 0, 0, 0);
                                cli_app_log(CLI_LOG_DEFAULT, "----------------no rsp add -------------\n");
                            } 
                            else
                            {
                                cli_app_log(CLI_LOG_ERROR, "CLI_MAIN: Wrong id %d from init device\n", id);
                            }
							
                            buffer_free(buf_tmp);
			                break;
                        } 
                        else 
                        {
                            cli_app_log(CLI_LOG_NOTICE, "----------------no rsp add -------------\n");
                           	//should not happen, or ignore this message.
                            break;
                        }
                    }

                    //device init response.
                    if ((buf_tmp = buffer_allocate()) == NULL) 
                    {
                        buffer_free(buf);
                        break;
                    }

                    conf_req = device_handle_response(buf, (I32 *) buf_tmp);
                    if (conf_req != RESPONSE_SET_RESPONSE) 
                    {
                        // here will be an RESPONSE_SET_CONTINUE, ignore it, just print out a warning.
                        cli_app_log(CLI_LOG_ERROR,"CLI_MAIN: Wrong event %08x get from device in init phase.\n", conf_req);
						
                        buffer_free(buf);
                        buffer_free(buf_tmp);
                        break;
                    }
                    
                    rsp = (DEV_SET_RSP *) buf_tmp;
                    if (cmd_queue_del(rsp->dcode, rsp->id, &socket, &type) < 0)
					{
                        cli_app_log(CLI_LOG_ERROR, "dev init, error clear command queue\n");
                    }

                    if (rsp->code != PARA_VALUE_RESULT_SUCCESS) 
					{
						//should not be here, all configuration is verified by last boot.
						//just log out what happened.
                        cli_app_log(CLI_LOG_ERROR, "dev init, Command fail response from device, code %08x, id %d\n", rsp->dcode, rsp->id);
                    }
                   
					if ( id != rsp->id)
					{
                        buffer_free(buf);
                        buffer_free(buf_tmp);
						cli_app_log(CLI_LOG_INFO, "this init msg is last init msg, give up this msg . and wait init msg\n ");
						break;
					}
						
                    if (device_get_init_status() != DEV_INIT_STAT_LAST) 
					{
                        id = device_handle_init_all(&dev_conf, buf_tmp, &dcode);
                  
						//should not happen, or break out and hung at main thread.
                        if (id == IF_APP_ERROR) 
						{
							if (device_get_init_status() != DEV_INIT_STAT_LAST) 
							{
								cli_app_log(CLI_LOG_ERROR, "dev init, init device error\n");
                            } 
                            else 		
							{
                            	cli_app_log(CLI_LOG_NOTICE, "DEV INIT Done\n\n");
								device_set_init_state(DEV_INIT_STAT_DONE);
									//last step, get dev sys info
								id = device_handle_request (REQUEST_GET_SYS_INFO, &dev_conf, buf, NULL, &dcode);
								cmd_queue_add(0, 0, TIMEOUT_CMD_QUEUE, dcode, id, 0);
                                
                                timer_queue_add(TIMEOUT_GET_STATUS(atoi(dev_conf.mng.itvl)), TIMER_ID_GET_STATUS, 0, 0, 0, 0);
                                timer_queue_add(TIMEOUT_DEV_DEAD(atoi(dev_conf.mng.itvl)), TIMER_ID_DEV_DEAD, 0, 0, 0, 0); 
                                timer_queue_add(TIMEOUT_INTERNAL_HEARTBEAT, TIMER_ID_INTERNALE_HB, 0, 0, 0, 0);
                                
                                if (strcmp(dev_conf.dev.protocol, HUANSHUO) == 0)
                                {
                                    timer_queue_add(CLI_APP_1S * 120, TIMER_ID_UDP_HEARTBEAT, 0, 0, 0, 0);
                                }
                                
                                if (strcmp(dev_conf.dev.protocol, BAIZHUO) == 0)
                                {
                                    timer_queue_add(CLI_APP_1S * 10, TIMER_ID_UDP_HEARTBEAT, 0, 0, 0, 0);
                                    timer_queue_add(CLI_APP_1S * 10, TIMER_ID_UDP_SN_DATA, 0, 0, 0, 0);
                                    if (atoi(dev_conf.capWifi.isSupported) == 1)
                                    {
                                        timer_queue_add(CLI_APP_1S * 20, TIMER_ID_UDP_MAC_DATA, 0, 0, 0, 0);
                                    }
                                }

                                if (strcmp(dev_conf.dev.protocol, FENGHUO) == 0)
                                {
                                    timer_queue_add(CLI_APP_1S * 10, TIMER_ID_FTP_PLACE_GET_DATA, 0, 0, 0, 0);
                                    timer_queue_add(CLI_APP_1S * 15, TIMER_ID_FTP_COMPANY_GET_DATA, 0, 0, 0, 0);
                                    timer_queue_add(CLI_APP_1S * 30, TIMER_ID_FTP_DEVSTATE_GET_DATA, 0, 0, 0, 0);
                                    timer_queue_add(CLI_APP_1S * 60, TIMER_ID_FTP_SITESTATE_UPLOAD, 0, 0, 0, 0);
                                    timer_queue_add(CLI_APP_1S * 20, TIMER_ID_FTP_TERMINAL_GET_DATA, 0, 0, 0, 0);

                                }
                                if (strcmp(dev_conf.dev.protocol, RENZIXING) == 0)
                                {
                                    timer_queue_add(CLI_APP_1S * 10, TIMER_ID_FTP_PLACE_GET_DATA, 0, 0, 0, 0);
                                    timer_queue_add(CLI_APP_1S * 30, TIMER_ID_FTP_DEVSTATE_GET_DATA, 0, 0, 0, 0);

                                }

                                if (atoi(dev_conf.dev.uploadMode) == 2)
                                {
                                    timer_queue_add(atoi(dev_conf.ftp.ftptimer) * CLI_APP_1S, TIMER_ID_FTP_GET_DATA, 0, 0, 0, 0);
                                    if (atoi(dev_conf.ftp.ftpMacenable) == 1)
                                    {
                                         timer_queue_add(atoi(dev_conf.ftp.ftpMactimer) * CLI_APP_1S, TIMER_ID_FTP_MAC_GET_DATA, 0, 0, 0, 0);
                                    }
                                }

                                if ( atoi(dev_conf.capLte.isSupported) == 1 )
                                {
                                    if ( atoi(dev_conf.capLte.tac_cycle) >= 10 )
                                    {
                                        timer_queue_add(TIMEOUT_CHNG_TAC_CYCLE(atoi(dev_conf.capLte.tac_cycle)), TIMER_ID_CHNG_TAC_CYCLE, 0, 0, 0, 0);
                                    }
                                    timer_queue_add(TIMEOUT_REQUEST_BBU_STATE, TIMER_ID_REQUEST_BBU_STATE, 0, 0, 0, 0);                  
                                    timer_queue_add(TIMEOUT_STATISTICS_INTVL(atoi(dev_conf.mng.cycle)), TIMER_ID_STATISTICS_INTERVAL, 0, 0, 0, 0); 

                                    //for working start and stop
                                    if (atoi(dev_conf.workMode.workMode) == 2)
                                    {
                                        timer_queue_add(atoi(dev_conf.workMode.workPeriod) * 1000, TIMER_ID_WORKPERIOD, 0, 0, 0, 0);
                                    }     
                                }
                            }
                        }
                        else 
						{
                            cmd_queue_add(0, 0, TIMEOUT_CMD_QUEUE, dcode, id, 0);
                           
						}
                   	}
                    
                    buffer_free(buf);
                    buffer_free(buf_tmp);

					break;
                case IF_APP_EVENT_INIT_CLI:
                    handle_recv_data_from_cli(&cli_rst_times, &fcode, &type);

                    break;
                case IF_APP_EVENT_LOCAL_CONFIG:
		                 
                    if ((buf = buffer_allocate()) == NULL) 
                    {
                        cli_app_log(CLI_LOG_CRITICAL, "init_cli: get buffer fail\n");
                        break;
                    }
                    
                    //send local config to server
                    if (cli_get_mng_status() == MNG_SERVER_STATUS_CONNECTED)
                    {
                        len = cmd_gen_local_config_response(1, buf, &dev_conf);
                        if (len == LOCAL_CONFIG_END)
                        {
                            buffer_free(buf);
                            break;
                        }
                    
                        if (timer_queue_find(TIMER_ID_CFG_FB) < 0)
                        {
                            timer_queue_add(TIMEOUT_CFG_FB, TIMER_ID_CFG_FB, 0, 0, 0, 0);
                            cli_send_to_mng(buf, len);
                        }
                    }

                    buffer_free(buf);
                    break;

                case IF_APP_EVENT_MNG_SERVER:
                    handle_recv_data_from_mng(&addDevNum, &historical_data, &numRcv[0], &fcode, &dcode, &type, &id);

                    break;
                case IF_APP_EVENT_DATA_SERVER:
                    if (strcmp(dev_conf.dev.protocol, ZHONGDUN) == 0)
                    {
                        handle_recv_data_from_data(&addDevNum, &historical_data, &numRcv[0], &fcode, &dcode, &type, &id);
                    }
                    else
                    {
                        if ((buf = event_queue[event_queue_e].data) == NULL || (buf_len = event_queue[event_queue_e].len) == 0) 
                        {
                            break;
                        }

                        buf[buf_len] = 0;

                        cli_app_log(CLI_LOG_INFO, "rcved data packets, data is %s\n", buf);
                        //heartbeat is the same as mng server, just use it as reference.

                        //check if heartbeat. will not handle at this time. fuction might be changed.
                        tmp_len = cmd_check_msg_num(buf, buf_len);
                        cli_app_log(CLI_LOG_INFO, "one msg Len is %d  total msg len is %d \n", tmp_len, buf_len);

                        if (buf_len > tmp_len)
                        {
                            if ((msg_tmp = buffer_allocate()) == NULL) 
                            {						
                                buffer_free(buf);
                                break;
                            }

                            memcpy(msg_tmp, buf+tmp_len, buf_len - tmp_len);
                            event_queue_add(IF_APP_EVENT_DATA_SERVER, event_queue[event_queue_e].socket, buf_len - tmp_len, msg_tmp);
                        }

                        cli_req = cmd_handle_mng_heartbeat_string(buf);

                        if (cli_req == IF_APP_PARSE_ERROR)
                        { 
                            cli_app_log(CLI_LOG_WARNING, "recevice a msg which is not a json format msg\n");
                            buffer_free(buf);
                            break;
                        }
                        else if (cli_req != IF_APP_ERROR) 	
                        {
                            cli_app_log(CLI_LOG_INFO, "DATA server heartbeat, code is %d\n", cli_req);

                            timer_queue_update(TIMER_ID_DATA_DEAD,TIMEOUT_SRV_DEAD(atoi(dev_conf.mng.hb)));

                            buffer_free(buf);
                            upload_data = true;
                            break;
                        }

                        if (cmd_handle_upload_result(buf) == IF_APP_OK) 
                        {
                            if ( timer_queue_del(TIMER_ID_SYNC_FEEDBACK) == 0 )
                            {
                                //set up_time to last data;

                                fd_times = 0;
                                up_back_time = 1;
                                if ( historical_data == 2)
                                {
                                    historical_data = 0;

                                    cli_app_log(CLI_LOG_INFO, "move to next period \n");
                                    //store remains packets to backup.
                                    memcpy(up_back, up_cache, updata->len + sizeof(UPDATA_CACHE) - 4);
                                }
                            }

                            if ( (uploadList = RestListByUptime(cmd_get_upload_srctime(buf), DATA_TYPE_IMSI)) != NULL )
                            { 
                                if ( timer_queue_del(uploadList->timerId) != 0 )
                                {
                                    cli_app_log(CLI_LOG_WARNING, "del upload timer fialed 0x%x \n", uploadList->timerId);
                                }
                                delDbRecord(uploadList->startId, uploadList->endId, DATA_TYPE_IMSI);
                            }
                        
                            if ( (uploadList = RestListByUptime(cmd_get_upload_srctime(buf), DATA_TYPE_MAC)) != NULL)
                            {
                                if ( timer_queue_del(uploadList->timerId) != 0 )
                                {
                                    cli_app_log(CLI_LOG_WARNING, "del upload timer fialed 0x%x \n", uploadList->timerId);
                                }
                                delDbRecord(uploadList->startId, uploadList->endId, DATA_TYPE_MAC);

                            }

                        }
                        else 
                        {
                            cli_app_log(CLI_LOG_ERROR, "upload data wrong\n");
                        }

                        buffer_free(buf);
                    }
					break;
				case IF_APP_EVENT_TIMER:
          
					timer_queue_timeout(CLI_APP_TICKS);
            
                    break;
				case IF_APP_EVENT_TIMEOUT:

                    handle_cli_internal_timer(&addDevNum, &historical_data, &socket, &cli_rst_times, &numRcv[0], &fcode, &dcode, &type, &id);

                    break;


                case IF_APP_EVENT_UDP_SERVER:
                    if ((buf = event_queue[event_queue_e].data) == NULL || (buf_len = event_queue[event_queue_e].len) == 0) 
                    {
                        break;
                    }
                    if (strcmp(dev_conf.dev.protocol, NANFEI) != 0)
                    {
                        buf[buf_len] = 0;
                        cli_rst_times = 0;
                        cli_app_log(CLI_LOG_INFO, "msg is : %s \n", buf);

                        buffer_free(buf);
                    }
                    else
                    {
                         handle_recv_data_from_mng(&addDevNum, &historical_data, &numRcv[0], &fcode, &dcode, &type, &id);
                    }
                    break;

                case IF_APP_EVENT_HANDLE_EUTRAN :
                    if (cmd_queue != NULL || cmdList.commandNum != 0)
                    {
                        timer_queue_add(TIMEOUT_CMD_PENDING, TIMER_ID_PENDING_CMD,
					                    event_queue[event_queue_e].module,
								        event_queue[event_queue_e].socket,
								        event_queue[event_queue_e].len,
								        event_queue[event_queue_e].data);
                         break;
                    } 

                    if ((buf = buffer_allocate()) == NULL)
                    {
                        cli_app_log(CLI_LOG_ERROR, "can not get buffer in case IF_APP_HANDLE_EUTRAN_MSG\n");
                        break;
                    }
                    if ((buf_tmp = buffer_allocate()) == NULL)
                    {
                        buffer_free(buf);
                        cli_app_log(CLI_LOG_ERROR, "can not get buffer in case IF_APP_HANDLE_EUTRAN_MSG\n");
                        break;
                    }

                    *((I32 *)buf_tmp) = event_queue[event_queue_e].len;
                    switch (event_queue[event_queue_e].socket) 
					{
                        case REQUEST_EUTRAN_CONFIG_CELL:
                            cli_app_log(CLI_LOG_INFO, "send config cell to cell[%d] \n", *(I32 *)buf_tmp);
                            id = device_handle_request(REQUEST_EUTRAN_CONFIG_CELL, &dev_conf, buf, (I32 *)buf_tmp, &dcode);
                            if (id >= 0)
                            {
                                 dev_status.bbuStatus[*(I32 *)buf_tmp - 1] .bbuState= BBU_SNFING;
                            	 cmd_queue_add(0, 0, TIMEOUT_CMD_QUEUE, dcode, id, 0);
                                 timer_queue_add(TIMEOUT_SNIFFER_DOING, TIMER_ID_SNIFFER_DOING,0, 0, 0, 0);
                                 timer_queue_add(TIMEOUT_BBU_CONFIG_CELL, TIMER_ID_BBU_CONFIG_CELL, 0, 0, 0, 0);
                            }

                            break;
                         case REQUEST_EUTRAN_TX_POWER_CONFIG:
                             cli_app_log(CLI_LOG_INFO, "send tx power to cell[%d] \n", *(I32 *)buf_tmp);

							 id = device_handle_request(REQUEST_EUTRAN_TX_POWER_CONFIG, &dev_conf, buf, (I32 *)buf_tmp, &dcode);
                             if (id >= 0) 
							 {
                            	  cmd_queue_add(0, 0, TIMEOUT_CMD_QUEUE, dcode, id, 0);
                                  timer_queue_add(TIMEOUT_CMD_NO_RSP, TIMER_ID_CMD_NO_RSP, 0, 0, 0, 0);
                                  timer_queue_add(TIMEOUT_BBU_CONFIG_CELL, TIMER_ID_BBU_POWER_CONFIG, 0, 0, 0, 0);
                             }

                             break;     
                        case REQUEST_SHUTDOWN_ALLPOWER:
                             cli_app_log(CLI_LOG_INFO, "send tx11 power to cell[%d] \n", *(I32 *)buf_tmp);

							 id = device_handle_request(REQUEST_SHUTDOWN_ALLPOWER, &dev_conf, buf, (I32 *)buf_tmp, &dcode);
                             if (id >= 0) 
							 {
                            	  cmd_queue_add(0, 0, TIMEOUT_CMD_QUEUE, dcode, id, 0);
                                  timer_queue_add(TIMEOUT_CMD_NO_RSP, TIMER_ID_CMD_NO_RSP, 0, 0, 0, 0);
                                  timer_queue_add(TIMEOUT_BBU_CONFIG_CELL, TIMER_ID_BBU_POWER_CONFIG, 0, 0, 0, 0);
                             }

                             break; 
                        case REQUEST_EUTRAN_AUTO_SNIFFER_PAR:
                            
                             for (slot_num = 0; slot_num < CELL_NUM ; slot_num++)
                             { 
                                  if ((dev_status.bbuStatus[slot_num] .bbuState == BBU_LOCATION) && (setautosnf[slot_num] == 0))
                                  {
                                      autoslot[slot_num] = 1;
                                      setautosnf[slot_num] = 1;
                                      break;
                                  }
                             }

                             //because FDD do not suporrt sniffer
                             if (slot_num >= 5) break;
                             cli_app_log(CLI_LOG_INFO, "start to set auto snf bbu[%d] \n", slot_num);
                             slot_num = 0;
                             memcpy(srvcmd, autoslot, sizeof(autoslot));

                             id = device_handle_request(REQUEST_EUTRAN_AUTO_SNIFFER_PAR, &dev_conf, buf, (I32 *)buf_tmp, &dcode);
                             if (id >= 0) 
							 {
                                 cmd_queue_add(0, 0, TIMEOUT_CMD_QUEUE, dcode, id, 0);
                                 timer_queue_add(TIMEOUT_CMD_NO_RSP, TIMER_ID_CMD_NO_RSP, 0, 0, 0, 0);
                             }

                             break;
                         case REQUEST_BBU_RADIO_OFF:
                             cli_app_log(CLI_LOG_INFO, "shutdown all bbu radio in one period   \n");

							 id = device_handle_request(REQUEST_BBU_RADIO_OFF, &dev_conf, buf, (I32 *)buf_tmp, &dcode);
                             if (id >= 0) 
							 {
                            	  cmd_queue_add(0, 0, TIMEOUT_CMD_QUEUE, dcode, id, 0);
                                  timer_queue_add(TIMEOUT_CMD_NO_RSP, TIMER_ID_CMD_NO_RSP, 0, 0, 0, 0);
                                  cli_app_log(CLI_LOG_DEFAULT, "----------------no rsp add -------------\n");
                             }

                             break; 
                         case REQUEST_BBU_RADIO_ON:
                             cli_app_log(CLI_LOG_INFO, "open all bbu radio in one period  \n");

							 id = device_handle_request(REQUEST_BBU_RADIO_ON, &dev_conf, buf, (I32 *)buf_tmp, &dcode);
                             if (id >= 0) 
							 {
                            	  cmd_queue_add(0, 0, TIMEOUT_CMD_QUEUE, dcode, id, 0);
                                  timer_queue_add(TIMEOUT_CMD_NO_RSP, TIMER_ID_CMD_NO_RSP, 0, 0, 0, 0);
                                  cli_app_log(CLI_LOG_DEFAULT, "----------------no rsp add -------------\n");
                             }

                             break; 
                         default:
                             break;
                    }   
                    
                    buffer_free(buf_tmp);
                    buffer_free(buf);
                    break;   
       
				case IF_APP_EVENT_DEVICE:
   
                    handle_event_from_device(&addDevNum, &historical_data, &socket, &cli_rst_times, &numRcv[0], &fcode, &dcode, &type, &id, updata, &manual_times);
                    break;

                case IF_APP_EVENT_CLI_STOP:
                    cli_app_log(CLI_LOG_ERROR, "Receive IF_APP_EVENT_CLI_STOP event\n");
                    //cli thread already removed error socket.
                    //so if auth/mng socket error, close all socket and restart them.
                    //if data socket error, did not hanle it, move to data heatbeat, 
                    //because of upload data timeout.

//                  if(event_queue[event_queue_e].socket == CLI_SOCK_ERR_MNG ||
//                     event_queue[event_queue_e].socket == CLI_SOCK_ERR_AUTH){
                    if (strcmp(dev_conf.dev.protocol, ZHONGDUN) == 0)
                    {
                        cleanZhongdunState();
                        if (event_queue[event_queue_e].socket == CLI_SOCK_ERR_MNG || event_queue[event_queue_e].socket == CLI_SOCK_MNG_REFUSED)
                        {
                            reconnectCode = MANAGER_SERVER_HB_LOST;
                            cli_app_log(CLI_LOG_NOTICE, "gsm mobile tcp socket error \n");
                            if ((timer_queue_find(TIMER_ID_MNG_DEAD) < 0) )
                                timer_queue_add(TIMEOUT_RESTART_CLI,TIMER_ID_MNG_DEAD, 0, 0, 0, 0);  
                            if (event_queue[event_queue_e].socket != CLI_SOCK_MNG_REFUSED && cli_get_data_status() == DATA_SERVER_STATUS_CONNECTED)
                            {
                                cli_rst_times++;
                                cli_app_log(CLI_LOG_NOTICE, "connect server failed time is %d \n", cli_rst_times);

                            }
                            timer_queue_del(TIMER_ID_MNG_HEART_BEAT);
                            
                        }
                        else if (event_queue[event_queue_e].socket == CLI_SOCK_ERR_DATA || event_queue[event_queue_e].socket == CLI_SOCK_DATA_REFUSED)
                        {
                            reconnectCode = DATA_SERVER_HB_LOST;
                            cli_app_log(CLI_LOG_NOTICE, "gsm unicom tcp socket error \n");
                            if ((timer_queue_find(TIMER_ID_DATA_DEAD) < 0) )
                                timer_queue_add(TIMEOUT_RESTART_CLI,TIMER_ID_DATA_DEAD, 0, 0, 0, 0); 
                            if (event_queue[event_queue_e].socket != CLI_SOCK_DATA_REFUSED && cli_get_mng_status() != MNG_SERVER_STATUS_CONNECTED)
                            {
                                cli_rst_times++;    
                                cli_app_log(CLI_LOG_NOTICE, "connect server failed time is %d \n", cli_rst_times);
                            }
                            timer_queue_del(TIMER_ID_MNG_HEART_BEAT);
                        }

                        if ( cli_rst_times >= 1440 && (atoi(dev_conf.workMode.workMode) == PARA_VALUE_WOKRING_TYPE_NORMAL))
                        {
                            cli_app_log(CLI_LOG_ERROR, "can not connect server times is %d so reboot system \n", cli_rst_times);
                            createRestartCauseFileByCode(CAN_NOT_CONNECT_NETWORK);
#ifndef MODULE_TEST
                            fflush(log);
                            system("reboot -f");
#endif                        
                        }

                    }
                    else
                    {
        

                        initRecordList();
                        initListGroud();

                        if (event_queue[event_queue_e].socket == CLI_SOCK_ERR_MNG)
                        {
                            reconnectCode = MANAGER_SERVER_HB_LOST;
                            timer_queue_del(TIMER_ID_DATA_DEAD);
                        }
                        else if (event_queue[event_queue_e].socket == CLI_SOCK_ERR_DATA)
                        {
                            reconnectCode = DATA_SERVER_HB_LOST;
                            timer_queue_del(TIMER_ID_MNG_DEAD);
                        }


                        if (update_ip == 1)
                        { 
                            update_ip = 2;
                            if ((buf = buffer_allocate()) == NULL) 
                            {
                                cli_app_log(CLI_LOG_CRITICAL, "cli_restart: get buffer fail\n");

                                break;
                            }

                            if (disable_auth == 0)
                            {
                                WD_AuthSDKFree();
                            } 

                            xml_config_overwirte(CONFIG_MODE_RESTORE);
                            xml_get_devConf(&dev_conf);    
                            timer_queue_add(TIMEOUT_RESTART_CLI,TIMER_ID_RESTART_CLI, 0, 0, 0, 0);  
                            buffer_free(buf);                    

                            break;                     
                        }

                        if (disable_auth == 0) WD_AuthSDKFree();

                        if ((timer_queue_find(TIMER_ID_RESTART_CLI) < 0) && (timer_queue_find(TIMER_ID_RESTART_AUTH) < 0)) 
                        {
                            cli_destroy_tcp_socket(CLI_TO_SRV_ALL_MASK);
                            timer_queue_add(TIMEOUT_RESTART_CLI,TIMER_ID_RESTART_CLI, 0, 0, 0, 0);  
                            //start timer to re-init client.                   
                        }

                        if ( event_queue[event_queue_e].socket != CLI_SOCK_CONNECT_REFUSED )
                        {
                            cli_rst_times++;
                        }
                        
                        if ( event_queue[event_queue_e].socket != CLI_SOCK_CONNECT_REFUSED && 
                                cli_rst_times >= 720 && (atoi(dev_conf.workMode.workMode) == PARA_VALUE_WOKRING_TYPE_NORMAL))
                        {
                            cli_app_log(CLI_LOG_ERROR, "can not connect server times is %d so reboot system \n", cli_rst_times);
                            createRestartCauseFileByCode(CAN_NOT_CONNECT_NETWORK);
#ifndef MODULE_TEST
                            I32 rebootTm = 5;
                            if ((buf = buffer_allocate()) == NULL) 
                            {
                                cli_app_log(CLI_LOG_CRITICAL, "cli_restart: get buffer fail\n");

                                break;
                            }
                            device_handle_request(REQUEST_UPDATA_REBOOT, &dev_conf, buf, &rebootTm, &dcode);
                            buffer_free(buf); 
                            sleep(10);
                            fflush(log);
                            system("reboot -f");
#endif                        
                        }
                    }
                    break;

                case IF_APP_EVENT_SYNC_CONF:
                    //todo: handle configuration sync
                    break;
            }

            if (++event_queue_e >= EVENT_QUEUE_SIZE) 
			{
                event_queue_e = 0;
            }
        }
      
    }

    return NULL;
}

static I32 cli_app_init()
{
    event_queue_init();
    cmd_queue_init();
    
    if (pthread_create(&cli_app_thread, NULL, cli_app_event_handler, NULL) != 0) 
    {
        cli_app_log(CLI_LOG_CRITICAL, "ERROR: Can't create device message receive thread\n");
        return -1;
    }

    return 0;
}

I32 cli_app_exit()
{

    pthread_cancel(cli_app_thread);
    pthread_join(cli_app_thread, NULL);
    cmd_queue_exit();
    event_queue_exit();
    return 0;
}

#ifdef IF_APP_UNIT_TEST
#if 0
#define CT_SLEEP				0x1071
#define CT_WAKEUP				0x1072
#define CT_WIRELISS_OFF			0x1073
#define CT_WIRELISS_ON			0x1074
#define CT_SMS_OFF				0x1075
#define CT_SMS_ON				0x1076
#define CT_SMS_SEND				0x1077
#define CT_SRV_UPDATA_OFF		0x1078
#define CT_SRV_UPDATA_ON		0x1079
#define CT_AIR_SNIFFER_OFF		0x107a
#define CT_AIR_SNIFFER_ON		0x107b
#define CT_TIME_SYNC			0x107c
#define CT_PA_PW_OFF			0x107d
#define CT_PA_PW_ON				0x107e
#endif

static I32 cli_app_unit_test(I32 log_lvl)
{
    U32 timer_delay;
    log_level = log_lvl;
    pthread_mutex_init(&mutex, NULL);
    unlink(log_file);
	cli_app_log(CLI_LOG_CRITICAL, "if_app ver 1.0 build %s %s\n", __DATE__, __TIME__);
    getRestartCauseFileCode();
	buf_msic_init();
    xml_cp_old_config();
    xml_cp_unchang_config();
    ftpInit();
    if (xml_get_devConf(&dev_conf) < 0) 
    {
        cli_app_log(CLI_LOG_CRITICAL, "Unit test: can not get device configuration file, Quit\n");

        if (xml_config_overwirte(CONFIG_MODE_RESTORE) < 0)
        {
            fflush(log);
            return -1;
        }
        if (xml_get_devConf(&dev_conf) < 0)
        {
            fflush(log);
            cli_app_log(CLI_LOG_CRITICAL, "Unit test: can not get device configuration file2, Quit\n");
            return -1;
        }
    }

    if ( !initsqlite() )
    {
        cli_app_log(CLI_LOG_CRITICAL, "Unit test: can not init sqilte,Quit \n");
        fflush(log);
        return -1;
    }
    if (strcmp(dev_conf.dev.protocol, ZHONGDUN) == 0)
        initZhongDunRecordPath();
    
    if (strcmp(dev_conf.dev.protocol, BAIZHUO) == 0 || strcmp(dev_conf.dev.protocol, NANFEI) == 0)
    {
        cli_app_log(CLI_LOG_NOTICE, "start to init udp thread\n");
        if (initUdpthread() != IF_APP_OK)
            return -1;
    }
    
    cli_app_log(CLI_LOG_INFO, "database init success \n");
    initRecordList();
    memset(&dev_status, 0, sizeof(DEV_STATUS));
    memset(&devVersion, 0, sizeof(VERSION));
    initListGroud();
   // xml_show_conf();
    if (atoi(dev_conf.auth.disable_auth) != 1)
        MAX_DATA_PER_FRAME = 300;
    else
        MAX_DATA_PER_FRAME = 100;
 
    //from now on, log system can be started.

    cli_app_init();

    event_queue_add(IF_APP_EVENT_INIT_DEV, 0, 0, NULL);
	
    while (device_get_init_status() != DEV_INIT_STAT_DONE)
	{
        usleep(10000);
	}

	while(dev_mac[0] == 0) 
	{
		usleep(10000);
	}
    //wait for bbu init

    //event_queue_add(IF_APP_EVENT_GET_BBU_INFO, 0, 0, NULL);

    //first init, need create thread.

   
    event_queue_add(IF_APP_EVENT_INIT_CLI, CLI_THREAD_CREATING, 0, NULL);

    timer_delay = CLI_APP_TICKS * 1000;
    while (1) 
	{
        usleep(timer_delay);
        event_queue_add(IF_APP_EVENT_TIMER, 0, 0, NULL);

    }
    return 0;
}
#endif
int main(int argc, char *argv[])
{
    I32 log_lvl = CLI_LOG_DEFAULT;
    I8 *par1, *par2;
    I32 tmp;

    if (argc == 3) 
	{
        par1 = argv[1];
        par2 = argv[2];
		
        if (strcmp(par1, "-l") == 0) 
		{
            tmp = atoi(par2);
            if (tmp < CLI_LOG_EMERG || tmp > CLI_LOG_DEFAULT)
                return -1;
            log_lvl = tmp;
        }
    } 

    struct stat logStat;
    tmp = stat(log_file, &logStat);
    if ( tmp != -1 )
    {
        I8 name[128] = {0};
        sprintf(name, "%s.old", log_file);
        remove(name);
        rename(log_file, name);
    }

#ifdef IF_APP_UNIT_TEST
    cli_app_unit_test(log_lvl);
    return 0;
#endif
    cli_app_exit();
    cli_exit();

    device_interface__exit();
    buf_msic_exit();

    return 0;
}

__inline void lockThread()
{
    pthread_mutex_lock(&mutex);
}

__inline void unlockThread()
{
    pthread_mutex_unlock(&mutex);
}

__inline const I8 *shortname(const I8 *filename)
{ 
    return strrchr(filename, '/') != 0 ? strrchr(filename, '/')+1 : filename;
}


__inline void cli_app_savelog(I32 level, const I8 *filename, U32 line,  I8 *fmt, ...)
{
    static I32 lineNum = 0;
    va_list ap;
    time_t rawtime;
    struct tm p = { 0 };
   
    if (level > log_level) 
	{
        return ;
    }

    lineNum++;
	if (log == NULL) 
	{
        log = fopen(log_file, "a");
        if ( log == NULL )
        {
            fprintf(stderr, "Open log_file:%s failed!!\n", log_file);
            return ;
        }
    }

    time(&rawtime);
    localtime_r(&rawtime, &p);

    fprintf(log, "%04d/%02d/%02d %02d:%02d:%02d %s[%d] %s %d ", (1900 + p.tm_year),
            (1 + p.tm_mon), p.tm_mday, p.tm_hour, p.tm_min, p.tm_sec, filename, line, loglevel[level],  lineNum);

    va_start(ap, fmt);
    vfprintf(log, fmt, ap);
    va_end(ap);

    fflush(log);
    if ( lineNum >= 30000 )
    {
        fclose(log);
        lineNum = 0;
        I8 name[128] = {0};
        sprintf(name, "%s.old", log_file);
        remove(name);
        rename(log_file, name);
        log = fopen(log_file, "a");
        while((dup2(STDOUT_FILENO, STDERR_FILENO) == -1) && (errno== EINTR))
        {
        };
    }    

    return ;
}
